Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if query string has values in Express.js/Node.js?

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');
}
like image 986
blundin Avatar asked Oct 10 '14 05:10

blundin


People also ask

How do I check if a query string parameter exists?

Check if a query string parameter existsThe URLSearchParams.has() method returns true if a parameter with a specified name exists.

How do you get variables in Express js in the GET method?

In Express. js, you can directly use the req. query() method to access the string variables. As per the documentation, the req.


2 Answers

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.
like image 162
Ravi Avatar answered Oct 10 '22 07:10

Ravi


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');
}
like image 33
Pranav Shekhar Jha Avatar answered Oct 10 '22 09:10

Pranav Shekhar Jha