How do I find original request path before redirect Express 4

可紊 提交于 2019-12-07 16:25:24

问题


Let's say I am trying to access the path http://localhost:3000/users#/WyCrYc28r/foo/1414585518343. But the path /users needs to be accessed only by the authenticated users as following:

  app.get('/users', isLoggedIn, function (req, res) {
      req.session.user = req.user;
      res.cookie('uid', req.session.passport.user)
          .render('users', { title: 'The Foo Machine', user: req.user });
  });

And following is the isLoggedIn middleware:

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

And following is how the login is being handled:

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/users', 
    failureRedirect: '/login', 
    failureFlash: true 
}));

I get redirected to the http://localhost:3000/users after logging in, but I want to the user to go to http://localhost:3000/users#/WyCrYc28r/foo/1414585518343 after successfully logging in as that was where the user wanted to go in the place place.

I am using PassportJS module for authentication/authorization here and have the front end developed in AngularJS.

Could somebody help me with it?


回答1:


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);
});


来源:https://stackoverflow.com/questions/26634451/how-do-i-find-original-request-path-before-redirect-express-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!