How do I find original request path before redirect Express 4

萝らか妹 提交于 2019-12-05 20:39:24

I can think of two common solutions to this pattern. Adding the angularjs in there may complicate things a little, but maybe this will get you started:

1) save the url as a query param in the redirect url

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/login?fromUrl='+req.originalUrl);
}

then after login you get that value and do the redirect, something like:

app.post('/login', passport.authenticate('local-login'), { failureRedirect: '/login', failureFlash: true },
  function(req, res) {
    res.redirect(req.param('fromUrl'));
});

2) (Not as easy or scalable) use your session state to store the from-url. it might look like:

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  req.session.fromUrl = req.originalUrl;
  res.redirect('/login');
}

then after login you get that value and do the redirect, something like:

app.post('/login', passport.authenticate('local-login'), { failureRedirect: '/login', failureFlash: true },
  function(req, res) {
    res.redirect(req.session.fromUrl);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!