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

时间:2015-06-18 17:08:59

标签: javascript node.js express passport.js

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

routes.js:

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

middleware.js:

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

按下按钮点击:

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

1 个答案:

答案 0 :(得分:3)

尝试:

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

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