Search code examples
node.jsexpressmiddleware

Cannot pass params between middlewares


I've searched for a way to pass data between middlewares in Express, and I've found this. Basically, the solution given is to create req.somevariable = variable1;.

As is told in the comments, req.somevariable throws undefined and the possible solution cosists on creating a previous middleware to initialize that variable.

Is there any simplier solution? I've also tried to do:

req.body.myVar = myVar;

But I still have the error about the var is undefined.

Thanks.


Solution

  • You can pass it easily. Just store it req object.

    app.get('/user', function(req, res, next) {
      req.id = "123456789";
      next();
    }, function (req, res, next) {
      var id = req.id;
      // do your working
    });