Reputation: 5083
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
.
Upvotes: 15
Views: 15583
Reputation: 31
If both the parameter and its values are to be treated case-insensitively then there's a simple approach:
const express = require('express');
const qs = require('qs');
const app = express();
app.set('query parser', function(str) {
// See https://github.com/ljharb/qs/blob/410bdd3c8ae7f5d7ae9b52648b8642b8adc5e1c0/dist/qs.js#L47
return qs.parse(typeof str === 'string' ? str.toUpperCase() : str, {});
});
That is, simply upper-case (or lower if you prefer) the entire query string before it is parsed.
Upvotes: 0
Reputation: 38346
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.
Upvotes: 15
Reputation: 203419
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();
});
Upvotes: 29