【问题标题】:How do I find original request path before redirect Express 4如何在重定向 Express 4 之前找到原始请求路径
【发布时间】:2014-12-25 09:35:08
【问题描述】:

假设我正在尝试访问路径http://localhost:3000/users#/WyCrYc28r/foo/1414585518343。 但是/users路径只有经过身份验证的用户才能访问,如下:

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

下面是isLoggedIn中间件:

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

以下是login 的处理方式:

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

登录后我被重定向到http://localhost:3000/users,但我希望用户在成功登录后转到http://localhost:3000/users#/WyCrYc28r/foo/1414585518343,因为那是用户想去的地方。

我在这里使用PassportJS 模块进行身份验证/授权,并在AngularJS 中开发了前端。

有人可以帮我吗?

【问题讨论】:

    标签: node.js express authorization httprequest passport.js


    【解决方案1】:

    对于这种模式,我可以想到两种常见的解决方案。在其中添加 angularjs 可能会使事情变得有点复杂,但也许这会让你开始:

    1) 将 url 保存为重定向 url 中的查询参数

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

    然后在登录后你得到该值并进行重定向,类似于:

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

    2) (不那么容易或可扩展)使用您的会话状态来存储 from-url。它可能看起来像:

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

    然后在登录后你得到该值并进行重定向,类似于:

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

    【讨论】:

    • 嘿,mattyice,req.originalUrl 给了我/users 的值,后来我用我尝试的第一个解决方案得到了TypeError: Cannot call method 'param' of null
    • 很有趣...所以在我的测试中 originalUrl 具有哈希后缀,所以我不确定那是什么。至于“参数”部分,我对护照 API 不太熟悉,我不得不放弃这里的示例 (passportjs.org/guide/authenticate)。我的例子似乎是合法的,但它显然没有向你传递那个请求对象。也许尝试删除第二个参数 "{ failureRedirect: '/login', failureFlash: true }" 作为测试?
    • 我将中间件isLoggedIn 移到了顶部,不知何故我得到了/login?fromUrl='+req.originalUrlreq.originalUrl 的哈希部分,但它仍然在控制台上为req.originalUrl 打印/users。而且我仍然收到我收到TypeError: Cannot call method 'param' of null 错误。删除 { failureRedirect: '/login', failureFlash: true } 没有任何区别。
    • 好的,是的,就像我说的,我不太了解护照 API。所有你需要某种方式来使用护照从req obj 设置重定向url,那部分应该可以工作。
    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多