2013-10-27 25 views
2

我有一個具有以下定義的服務器:添加中間件之後app.router

app.get('/', function(req, res) { 
    // gets something 
} 

app.post('/', function(req, res) { 
    // updates something, need to be authenticated 
} 

現在我想的post行動,只負責身份驗證的用戶,所以我想他們之間增加一個auth中間件這樣的:

app.get('/', function(req, res) { 
    // gets something 
} 

app.use('/', function(req, res) { 
    // check for authentication 
} 

app.post('/', function(req, res) { 
    // updates something, need to be authenticated 
} 

這樣,GET獲得通過併爲POST,用戶必須進行身份驗證。

問題是,快遞不會進入我的app.use中間件。如果我把app.use中間件放在所有app.VERB路由之前,它就可以工作。

有沒有辦法像我想要的那樣做?

回答

4

當你宣佈你的第一條路線,快速自動插入app.router到中間件鏈。由於路由器可以處理任何以下路由,所以在第一條路由之後聲明的任何中間件都不會處理您的路由。

,但使用的app.use,你可以使用一個事實,即路由處理器非常相似,中間件:

app.get('/', function(req, res) { 
    // gets something 
}); 

app.all('/', function(req, res, next) { // catches GET, POST, ... to '/' 
    // check for authentication 
}); 

app.post('/', function(req, res) { 
    // updates something, need to be authenticated 
}); 

但如果你只是有一個需要通過中間件傳遞一個路由,它有意義的是遵循@hiattp的建議並立即將中間件添加到路由聲明中。

+0

我想知道是否因爲我明確2.x因爲我確定我有變化之前已經在'app.VERB()'後面定義了'app.use()'並且它工作正常 – Michael

+0

@Michael用'express @ 2.5.1'進行了測試,似乎與3.x([gist ](https://gist.github.com/robertklep/bf45da5dc0a5947b237f)) – robertklep

+0

你也可以使用app.all('*') – Micah

2

我喜歡把這種類型的檢查在一個可重複使用的方法,並將其傳遞到路由處理:

function ensureAuth(req, res, next){ 
    if(req.user) next(); // Auth check 
    else res.redirect('/'); 
} 

app.post('/', ensureAuth, function(req,res){ 
    // User is authenticated 
} 
+0

這很好,雖然我將不得不把它放在我後來定義的每條路線中,如果你有很多路線,這是一種無賴 – Michael

相關問題