在我的Node.js应用程序(我正在使用express 4.x)中,我想检查用户是否已登录。如果未登录用户,我想重定向到我的登录页面。然后,我在中间件中这样做:

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

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

最佳答案

您陷入无限循环,因为即使请求的路径是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();
});

10-04 22:20
查看更多