user2791897 user2791897 - 4 months ago 19
Node.js Question

passing variables to the next middleware using next() in expressjs

Well my question is I want to pass some variable from first middleware to another middleware and I tried doing this but there was req.somevariable is a given as 'undefined'.




//app.js
..
app.get('/someurl/',middleware1,middleware2)
...





////middleware1
...
some conditions
...
res.somevariable = variable1;
next();
...





////middleware2
...
some conditions
...
variable = req.somevariable;
...





Thanks for answering.

Answer

Attach your variable to the req object, not res.

Instead of

res.somevariable = variable1;

Have:

req.somevariable = variable1;