Handling duplicate query string arguments in Express.js

Duplicate query string entries are somewhat common, for example if you use Solr, you can do something like this:

/execute?facet.field=stream_size&facet.field=content_type

If you make an Express.js endpoint, you get can this data through the “query” option:

app.use('/execute/', 
  function(req, res) {
    console.log(req.query)
  }
)

The “req.query” is a Javascript object, which presents difficulties with duplicated arguments, which are joined into an array (so you do lose some information about order).

If, for example, you wanted to combine all back into a string, you could do it with something like this (assuming you use underscore/lodash):

let args = req.query;

let queryString =
  _.join(
    _.keys(args)
     .map( 
       (arg) => 
         isArray(args[arg]) ? 
         _.join(
           args[arg].map( 
             (argv) => arg + '=' + argv 
           ), 
         '&') : 
         arg + '=' + args[arg]), 
    '&');

Leave a Reply

Your email address will not be published. Required fields are marked *