Search code examples
node.jspassport-localpassport.js

How to determine specific successRedirect in node js using express?


I have a question about successRedirecting in passport.authenticate. I'm using passport.js and local strategy in nodejs and express for user login and trying to make specific successRedirect route.

For example, if I log in with user id: gpaul(pretended to be successed logging in), then successRedirect route is wanted to be '?channel=gpaul'.

I made the code like below

var data_1 = {email:''};
app.post('/login',
  function (req,res,next){
    req.flash("email");
    data_1.email = req.body.email;
    console.log(data_1.email);
    next();
  }, passport.authenticate('local-login', {
    successRedirect : ('/status.html?channel='+ data_1.email),
    failureRedirect : '/login',
    failureFlash : true
  })
);

After implementing above code, the address comes out with blank , localhost:4000/?channel= How can I put that data_1.email into successRedirect?

Does anybody have any ideas for that...? Please help me out here..

Thanks.


Solution

  • Try using Custom Callback :

    app.post('/login', function(req, res, next) {
    passport.authenticate('local-login', function(err, user, info) {
      if (err) { return next(err); }
      if (!user) { return res.redirect('/login'); }
      return res.redirect('/status.html?channel='+ req.body.email);
      })(req, res, next);
    });
    

    In this implementation, callback has access to the req and res objects through closure. Therefore, email will not be empty (unlike your implementation)