简体   繁体   中英

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,

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');

One can also imagine that the left-hand side is not a variable or property, so it makes no sense to try to assign a value to it. If you want to change a query param you have to modify the property in the req.query object.

req.query.q = 'something';

The same goes for req.body and req.params .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM