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
.
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.
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.
Query parametersThe request query parameter names are 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.
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();
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With