Node Express - 重定向到登录视图

时间:2016-02-16 16:17:02

标签: node.js express

我正在尝试将我的快速应用程序配置为基于某些逻辑重定向到登录页面。我有以下内容:

  app.use('/', function(req, res, next){
    if(!req.session.accessToken){
      //do something here
    }
    next();
  });

我有一个login.html文件位于我的应用程序所在目录的根目录中,我只是不确定我需要在res对象上调用什么,例如redirectsend

另外,我知道上面的内容实际上会导致无限循环。

这里有什么正确的方法?

2 个答案:

答案 0 :(得分:1)

你要小心你的处理程序顺序,你想要的(如果你真的想要自己做这个而不是像Passport这样的东西)就像这样(有点骨架);

app.use('/login', function(req, res) {   // Allows access to login page
    res.send('displaying login page');   // before access token check
});

app.use(function(req, res, next) {       // Catches access to all other pages
    if(!req.session.accessToken) {       // requiring a valid access token
        res.redirect('/login');
    } else {
        next();
    }
});

// the rest of your routes go here, they should not be called unless authenticated

答案 1 :(得分:0)

最明显的答案是简单地调用res.redirect('/login.html'),但这会将301(永久移动)代码返回给浏览器。更加语义正确的解决方案可能是返回401(未经授权)并将login.html文件呈现给响应。

请参阅Is it possible to send a 401 Unauthorized AND redirect (with a Location)?

所以解决方案看起来像这样:

app.use('/', function(req, res, next){
  if(!req.session.accessToken)
    res.status(401).sendFile(path.join(__dirname+'/login.html'));
  else
    next()
});