We are migrating from ExpressJS 3 to ExpressJS 4, and we noted that the following APIs are being deprecated:
req.param(fieldName)
req.param(fieldName, defaultValue)
Is there a middleware that brings these APIs back, like other APIs that were 'externalized' from express to independent modules ?
EDITED: Clarification - The need is an API that provides an abstracted generic access to a parameter, regardless to if it is a path-parameter, a query-string parameter, or a body field.
The req. params property is an object that contains the properties which are mapped to the named route "parameters". For example, if you have a route as /api/:name, then the "name" property is available as req.params.name. The default value of this object is {}.
The req. params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id.
param() Returns the value of the parameter with the specified name.
query is a request object that is populated by request query strings that are found in a URL. These query strings are in key-value form.
Based on Express Documentation, we should use like this
On express 3
req.param(fieldName)
On express 4
req.params.fieldName
Personally i prefer req.params.fieldName
instead req.param(fieldName)
Why would you want to bring it back? There's a reason that it's been deprecated and as such you should probably move away from it.
The discussion on why they are deprecating the API is available at their issue tracker as #2440.
The function is a quick and dirty way to get a parameter value from either req.params
, req.body
or req.query
. This could of course cause trouble in some cases, which is why they are removing it. See the function for yourself here.
If you are just using the function for url parameters, you can just replace it with this a check for req.query['smth'] or 'default'
:
var param_old = req.param('test', 'default');
var param_new = req.query['test'] || 'default';
(Please note that an empty string is evaluated to false
, so they are not actually 100% equal. What you want is of course up to you, but for the most part it shouldn't matter.)
Ok, after reading the threads given in references by @Ineentho, we decided to come up with the following answer:
https://github.com/osher/request-param
A connect/express middleware to enable back the req.param(name,default) API deprecated in express 4
The middleware does not only brings back the goo'old functionality. It also lets you customize the order of collections from which params are retrieved , both as default rule, and as per-call :-)
Have fun!
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