How do I check if query string has values in Express.js/Node.js?
All you need to do is check the length of keys in your Object
, like this,
Object.keys(req.query).length === 0
Sidenote: You are implying the if-else in wrong way,
if (req.query !== {}) // this will run when your req.query is 'NOT EMPTY', i.e it has some query string.
If you want to check if there is no query string, you can do a regex search,
if (!/\?.+/.test(req.url) {
console.log('should have no query string');
}
else {
console.log('should have query string');
}
If you are looking for a single param try this
if (!req.query.name) {
console.log('should have no query string');
}
else {
console.log('should have query string');
}