How to check if a query string has values ​​in Express.js / Node.js?

How to check if a query string passed to an Express.js application contains any values? If I have an API URL that could be: http://example.com/api/objects or http://example.com/api/objects?name=itemName , which conditional statements work to determine with what am I doing?

My current code is below and it always evaluates the 'should be no string' option.

 if (req.query !== {}) { console.log('should have no query string'); } else { console.log('should have query string'); } 
+10
source share
3 answers

All you have to do is check the length of the keys in Object , e.g.

 Object.keys(req.query).length === 0 


Sidenote: You mean inappropriate if-else behavior,

 if (req.query !== {}) // this will run when your req.query is 'NOT EMPTY', ie it has some query string. 
+24
source

If you want to check if there are any query strings, you can search by regular expression,

 if (!/\?.+/.test(req.url) { console.log('should have no query string'); } else { console.log('should have query string'); } 

If you are looking for one option, try this

 if (!req.query.name) { console.log('should have no query string'); } else { console.log('should have query string'); } 
+3
source

We can use JS Library underscore

Which has a built-in function isEmpty (obj). This returns true / false.

So, the code will look like this: -

 const underscore = require('underscore'); console.log(underscore.isEmpty(req.query)); 
0
source

Source: https://habr.com/ru/post/1204397/


All Articles