Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

express - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...