2016-09-08 51 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(); 
});