2016-09-08 55 views
1

在我的Node.js应用程序(我使用Express 4.x)我想检查用户是否登录。如果用户没有登录,我想重定向到我的登录页面。然后,我做的是,在中间件这样的:节点js太多重定向使用中间件重定向

Server.js

app.use(function (req, res, next) { 

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated()) 
     return next(); 

    // if they aren't redirect them to the home page 
    res.redirect('/login'); 
}); 

登录路线

// Login page 
app.get('/login', function(req, res){ 
    res.render('pages/login', { 
       error : req.flash('loginError'), 
       info : req.flash('info'), 
       success : req.flash('success') 
      }); 
}); 

但是,当我在中间件添加此代码,登录页面被称为超过30次...并且我的浏览器显示Too many redirect

你知道为什么我的登录页面被称为很多吗?

+1

是req.isAuthenticated()也呼吁“/登录”?因为这是一个无限循环。 –

+0

我编辑了我的问题。 req.authenticated也不需要/ login。但我试图删除'if(req.isAuthenticated())return next();'来测试。我只是让'res.redirect('/ login');'和我有相同的错误 – John

+2

检查中间件,如果当前路径是'login',则不要重定向。并且为了更好的情况,在重定向之后调用'next' –

回答

2

你赶上无限循环,因为如果请求的路径是login即便如此重定向到login再次

app.use(function (req, res, next) { 

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated()) 
     return next(); 

    // if they aren't redirect them to the home page 
    if(req.route.path !== '/login') 
     res.redirect('/login'); 
    next(); 
});