身份验证后将用户重定向到上一页

时间:2022-10-20 10:09:00

I'm using Google auth through Passport in my app and I'm attempting to redirect the user back to the original page they requested after successful sign-in. I think that location.reload() may be the problem, but not sure how to solve it.

我在我的应用程序中通过Passport使用Google身份验证,并且我尝试将用户重定向回成功登录后他们请求的原始页面。我认为location.reload()可能是问题,但不知道如何解决它。

routes.js:

routes.js:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
  res.redirect(req.session.returnTo);
  req.session.returnTo = null;
});

middleware.js:

middleware.js:

var isAuth = function(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  } else {
    req.session.returnTo = req.url;
    return res.redirect('/');
  }
};

called on button click:

按下按钮点击:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    location.reload();
});

1 个解决方案

#1


3  

Try:

尝试:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
   var backURL = req.header('Referer') || '/';
   res.json({redir: backURL});
});

And:

和:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    window.location.href = data.redir;
});

#1


3  

Try:

尝试:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
   var backURL = req.header('Referer') || '/';
   res.json({redir: backURL});
});

And:

和:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    window.location.href = data.redir;
});