Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  30] [ 7]  / answers: 1 / hits: 46284  / 10 Years ago, fri, october 10, 2014, 12:00:00

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');
}

More From » node.js

 Answers
4

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.

[#69173] Wednesday, October 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
luna questions
;