Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Node.js req object parameters

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.

  1. A service that turns quick-links into full blown requests and proxies those out.
  2. Simply modifying the parameters before sending it off to another function that you have no desire to modify.

Onto the question, Is there a way to modify the req object parameters?

like image 881
Levi Roberts Avatar asked Sep 14 '13 12:09

Levi Roberts


2 Answers

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.

like image 195
Roy Reiss Avatar answered Nov 10 '22 20:11

Roy Reiss


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');
like image 3
Aqib Mumtaz Avatar answered Nov 10 '22 21:11

Aqib Mumtaz