我試圖加載所有我的網頁之前使用的authenticateUser()中間件res.redirect。 (在app.get('/',authenticateUser,function()...))中,我試圖在app.use(authenticateUser)之前調用app.use(app.router) )。Node.js的 - 問題與中間件
這並不然而工作。的authenticateUser基本上是:
if (req.session.loginFailed) {
next()
else {
if (req.session.user_id) {
...
if (userAuthenticated) {
next();
} else {
req.session.loginFailed = true;
console.log('setting loginFailed to true');
res.redirect('/login');
}
}
}
然後在app.get( '/登錄')我設置req.session.loginFailed爲假;
這應該工作,但我只想把它稱爲上app.get()或app.post()等爲我的實際網頁之一。我認爲它越來越稱爲很多次了許多不同的要求(因爲在加載一個頁面,「設置loginFailed到真正的」被多次調用)
有沒有更好的方式來做到這一點?還是應該在我網站上的每一頁之前簡單地調用它?
不夠公平,它很有趣,因爲我在實際工作離nodepad教程。事情是我的整個網站要求您登錄,所以我一起砍了一種方法,不必手動將其包含在所有路線中,但是如果這是正確的方式,我會將其包含在內。 – 2012-01-04 18:48:45
我同意@alessioalex。但是,如果您堅持已經制定的方法,請確保您的'app.use(authenticateUser)'是在會話中間件之後。 – danmactough 2012-01-04 14:03:58