Change parameters of a Node.js req object

So, as usual, I tried to find this question on SO, but still no luck.

I know that the answer is “Yes, you can change the req object”, but nothing is said about the parameters of the req object.

For example, the following code throws an error:

app.get('/search', function(req, res) { req.param('q') = "something"; }); 

Mistake:

 ReferenceError: Invalid left-hand side in assignment 


I suppose this has something to do with a property that does not have a “SET” method or something like that.

There are several scenarios where this may come in handy.

  • A service that turns quick links into full-execution requests and proxies.
  • Just change the settings before sending to another function that you do not want to change.

To the question, is there a way to change req object parameters?

+7
javascript express
source share
3 answers

Instead

 req.param('q') = "something"; 

You will need to use:

 req.params.q = "something"; 

The first tries to set the value for the return value of the param function, not the parameter itself.

It is worth noting that the req.param () method extracts the values ​​from req.body , req.params and req.query all at once and in that order, but to set the value you need to specify from which number it comes from:

 req.body.q = "something"; // now: req.param('q') === "something" req.query.r = "something else"; // now: req.param('r') === "something else" 

However, if you are not constantly changing something presented by the client, it may be better to place it somewhere else so that he is not mistaken for input from the client by any third-party modules that you use.

+19
source share

Alternative approaches to setting parameters in the 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 the parameters as follows:

  var model = req.param('model'); var name = req.param('name'); var ids = req.param('ids'); 
+2
source share

It can also be assumed that the left 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 the query parameter, you need to change the property in the req.query object.

 req.query.q = 'something'; 

The same applies to req.body and req.params .

+1
source share

All Articles