Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用中间件重定向的节点js太多重定向_Javascript_Node.js_Redirect_Express - Fatal编程技术网

Javascript 使用中间件重定向的节点js太多重定向

Javascript 使用中间件重定向的节点js太多重定向,javascript,node.js,redirect,express,Javascript,Node.js,Redirect,Express,在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 th

在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多次。。。我的浏览器显示
重定向太多


你知道为什么我的登录页面经常被调用吗?

你陷入了无限循环,因为如果请求的路径是
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();
});

req.isAuthenticated()是否也为“/login”调用?因为这是一个无限循环。我编辑了我的问题。req.authenticated也不是为/login调用的。但是我试图删除
if(req.isAuthenticated())return next()以进行测试。我只是让res.redirect('/login')
和我在中间件中有相同的错误检查,如果当前路径是
登录
,则不要重定向。为了更好的情况,请在之后调用
next
redirect@EbrahimPasbani很好的解决方案,非常感谢。很好,不客气