How do I check if a query string passed to an Express.js application contains any values? If I have an API URL that could be either: http://example.com/api/objects
or http://example.com/api/objects?name=itemName
, what conditional statements work to determine which I am dealing with?
My current code is below, and it always evaluates to the 'should have no string' option.
if (req.query !== {}) {
console.log('should have no query string');
}
else {
console.log('should have query string');
}
Check if a query string parameter existsThe URLSearchParams.has() method returns true if a parameter with a specified name exists.
In Express. js, you can directly use the req. query() method to access the string variables. As per the documentation, the req.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With