使用中间件redirect节点js太多redirect

在我的Node.js应用程序(我使用Express 4.x)我想检查用户是否login。 如果用户没有login,我想redirect到我的login页面。 然后我在中间件中这样做:

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路线

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

但是,当我在中间件中添加此代码时,login页面被调用超过30次…而且我的浏览器显示了Too many redirect

你知道为什么我的login页面被称为很多?

你陷入无限循环,因为如果请求的path是login即使redirect到再次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(); });