简体   繁体   English

使用 Express 和 Passport JS 在 Node 中重定向路由

[英]Redirecting routes in Node using Express and Passport JS

Lets say I have a route defined using Express Router for rendering the payment form:假设我有一个使用 Express Router 定义的路由来呈现付款表单:

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.我的登录会话是使用 Passport 构建的。 Here's how my POST login route looks like:这是我的 POST 登录路由的样子:

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.基本思想是存储您希望用户重定向到的 URL。 You can store it in the URL itself via GET parameters, or you can use sessions.您可以通过GET参数将其存储在 URL 本身中,也可以使用会话。

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:然后在您的/login路线中:

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' req.session.returnURL || 'back' makes sure if the returnURL doesn't exist on the session, 'back' would be used instead. req.session.returnURL || 'back'确保如果returnURL中不存在returnURL ,则将使用'back'代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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