sasha sasha - 4 months ago 30
Node.js Question

ExpressJS > router middleware > passing variable req.foo via redirect not working

Let's say I have this:

a) 2 routes with 1 middleware function each and a callback function:

router.post('/foo', fooCtrl, function(req, res)
{
res.redirect('/bar');
});

router.get('/bar', barCtrl, function(req, res)
{
res.end('finished');
});


b) 2 middleware function expressions

fooCtrl = function(req, res, next)
{

req.foo = 'foo';

next();
};

barCtrl = function(req, res, next)
{
console.log(req.foo); // output is 'undefined'

next();
};


As you can see, in the fooCtrl I'm setting a variable req.foo - and in this scope it is set than... but I'm not able to call this variable in the barCtrl-scope.

Isn't the req object passed by reference?

Any suggestions or best practices?

The purpose of this is to pass a token after login from the login-controller to an admin-controller .. something like that.

Answer

That is the expected behaviour. req object is created anew for each new request and your redirection i.e. res.redirect('/bar') results in a new request.

Solution: You may use some package e.g.connect-flash which stores variables in a temporary session object, which can be used only once. You need to set required values in your flash objects before redirecting. Then after redirection, you will be able to get the saved values from the flash object itself.

Comments