2015-06-20 60 views
2

我試圖阻止用戶在登錄時訪問某些頁面,但未使用node.js登錄。如何重定向,然後在node.js中停止

到目前爲止,我有這樣的想法:

exports.blockIfLoggedIn = function (req, res) { 
    if (req.isAuthenticated()) { //passport 
     req.flash('error', 'Sorry but you can\'t access this page'); 
     res.redirect('/'); 
    } 
}; 

MA.f.auth.blockIfLoggedIn(req, res, next); 
res.render('users/login', { 
    title: 'Login' 
}); 

這將重定向頁面,但它也將錯誤在控制檯:

Error: Can't set headers after they are sent. 

我明白,這是試圖做res.render('users/login')功能,但我已經將頁面設置爲redirect(/),所以它不能。

必須有某種方式,如果req.isAuthenticated()是真的,它會重定向,然後本質上做類似於php的exit()

回答

2

您應該使用中間件。這裏有一個例子:

// you can include this function elsewhere; just make sure you have access to it 
var blockIfLoggedIn = function (req, res, next) { 
    if (req.isAuthenticated()) { 
     req.flash('error', 'Sorry, but you cannot access this page.') 
     return res.redirect('/') 
    } else { 
     return next() 
    } 
} 

// in your routes file (or wherever you have access to the router/app) 
// set up your route 
app.get('/users/login', blockIfLoggedIn, function (req, res) { 
    res.render('somePage.ext', { title: 'Login' }) 
})