Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs (express) is it possible to have case insensitive querystring?

It seems that querystring is case sensitive. Is it possible to have a case insensitive querystring?

If my url has ?Id=10, accessing req.query.id returns undefined.

like image 908
Amitava Avatar asked Mar 20 '13 11:03

Amitava


People also ask

Is Querystring case-sensitive?

If the query string is built as a result of an HTML form submission, the keys (names) come from the value of the form controls name attribute, which the HTML specs say is case-sensitive.

Is Express JS case-sensitive?

Case-insensitive routing (ExpressJS) The Express server framework allows developers to easily define routes for serving static pages or RESTful APIs; however, these routes are case-insensitive by default.

Should query params be case-insensitive?

Query parametersThe request query parameter names are case-sensitive.

Is Nodejs case-sensitive?

Yes, it is a case sensitive language, which means the identifiers, keywords, variables, and function names must be written with a consistent capitalization of letters.


2 Answers

It's not possible as-is, but you could insert a very simple middleware which would, for instance, lowercase all keys in req.query:

// insert this before your routes
app.use(function(req, res, next) {
  for (var key in req.query)
  { 
    req.query[key.toLowerCase()] = req.query[key];
  }
  next();
});
like image 62
robertklep Avatar answered Sep 20 '22 12:09

robertklep


With the solution proposed by Robert, be aware that whenever you read from req.query, you will need to use lowercased keys. This makes future additions to your API error prone.

Here is an alternative piece of middleware, using a Proxy object to modify the behavior of req.query[...], so that lookups are case insensitive:

app.use((req, res, next) => {
  req.query = new Proxy(req.query, {
    get: (target, name) => target[Object.keys(target)
      .find(key => key.toLowerCase() === name.toLowerCase())]
  })

  next();
});

Besides being less error prone, this approach also leaves the req.query intact for enumerating operations, where the original solution would potentially create duplicate key/value pairs.

like image 42
Jørn Schou-Rode Avatar answered Sep 20 '22 12:09

Jørn Schou-Rode