So as usual, I tried to find this question on SO but still no luck.
I am aware that the answer is "Yes, you CAN modify the req object" but nothing is said about the req object parameters.
For example the following code will throw an error:
app.get('/search', function(req, res) {
req.param('q') = "something";
});
Error:
ReferenceError: Invalid left-hand side in assignment
I imagine this has something to do with the property not having a 'SET' method or something along those lines.
There are a few scenarios where this could come in handy.
Onto the question, Is there a way to modify the req object parameters?
Rather than:
req.param('q') = "something";
You'll need to use:
req.params.q = "something";
The first one is trying to set a value on the return value of the param function, not the parameter itself.
It's worth noting the req.param() method retrieves values from req.body
, req.params
and req.query
all at once and in that order, but to set a value you need to specify which of those three it goes in:
req.body.q = "something";
// now: req.param('q') === "something"
req.query.r = "something else";
// now: req.param('r') === "something else"
That said unless you're permanently modifying something submitted from the client it might be better to put it somewhere else so it doesn't get mistaken for input from the client by any third party modules you're using.
Alternative approaches to set params in request (use any):
req.params.model = 'Model';
Or
req.params['model'] = 'Model';
Or
req.body.name = 'Name';
Or
req.body['name'] = 'Name';
Or
req.query.ids = ['id'];
Or
req.query['ids'] = ['id'];
Now get params as following:
var model = req.param('model');
var name = req.param('name');
var ids = req.param('ids');
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