简体   繁体   中英

Redirecting routes in Node using Express and Passport JS

Lets say I have a route defined using Express Router for rendering the payment form:

router.get('/payment', (req, res) => {
  if (req.user) {
    res.render('payment', { user: req.user });
  } else {
    res.redirect('/login');
  }
});

If I am not logged in then I should be taken to the login page, when I login, I want to be redirected back to the payment form.

My login session is built using Passport. Here's how my POST login route looks like:

router.route('/login').post((req, res, next) => {
  req.assert('email', 'Please sign up with a valid email.').isEmail();
  req.assert('password', 'Password must be at least 4 characters long').len(4);

  var errors = req.validationErrors();
  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/login');
  }

  passport.authenticate('login', {
    successRedirect: 'back',
    failureRedirect: '/login',
    failureFlash : true
  })(req, res, next);
});

On success, I am redirecting back to previous page, but this takes me to the homepage, which makes sense. I am not sure on login success, how I can redirect user to the payment form.

There are couple of ways you can do this. The basic idea is to store the URL you want the user to be redirected to. You can store it in the URL itself via GET parameters, or you can use sessions.

That's the whole idea.

For example, to use sessions:

router.get('/payment', (req, res) => {
  if (req.user) {
    res.render('payment', { user: req.user });
  } else {
    req.session.returnURL = '/payment';
    res.redirect('/login');
  }
});

Then in your /login route:

router.route('/login').post((req, res, next) => {
  req.assert('email', 'Please sign up with a valid email.').isEmail();
  req.assert('password', 'Password must be at least 4 characters long').len(4);

  var errors = req.validationErrors();
  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/login');
  }

  passport.authenticate('login', {
    successRedirect: req.session.returnURL || 'back',
    failureRedirect: '/login',
    failureFlash : true
  })(req, res, next);
});

The line req.session.returnURL || 'back' req.session.returnURL || 'back' makes sure if the returnURL doesn't exist on the session, 'back' would be used instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM