18

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');
}
blundin
  • 1,603
  • 3
  • 14
  • 29
  • 1
    Not sure of `node`'s support of this, but maybe you could use [this answer](http://stackoverflow.com/a/5533226/2708970) to check if the length of `req.query` is greater than 0. – Brendan Oct 10 '14 at 05:08
  • Are you using express? – JME Oct 10 '14 at 05:11

4 Answers4

44

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.
Ravi
  • 1,320
  • 12
  • 19
8

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

We can use underscore JS Library

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

So, the code will look like :-

const underscore = require('underscore');
console.log(underscore.isEmpty(req.query));
Nikhil Vats
  • 291
  • 3
  • 7
1

I usually check if the variable in the query string is defined. Using the url package in ExpressJS it would be so:

var aquery = require('url').parse(req.url,true).query;

if(aquery.variable1 != undefined){
  ...
  ....
  var capturedvariablevalue = aquery.variable1;
  ....
  ....

}
else{
  //logic for variable not defined
  ...
  ...
  //
}
pcodex
  • 1,812
  • 15
  • 16