2012-11-14 86 views
0

在我ExpressJS的應用程序,我的幾個網址的處理程序有以下邏輯:ConnectJS/ExpressJS url處理程序的常用預處理程序?

  1. 檢查用戶是否有權訪問資源
  2. 如果是這樣,繼續
  3. 否則,重定向到主處理器。

有沒有辦法通過ConnectJS或ExpressJS插入某些url處理程序的預處理程序?

我知道我可以在全球範圍內爲所有處理程序(我從IE的XDR中插入缺失的標頭)執行此操作。

但是,我可以爲處理程序的子集執行此操作嗎?

回答

3

我做這樣的事情:

的lib/auth.js

exports.checkPerm = function(req, res, next){ 
    //do some permission checks 
    if (authorized) { 
    next(); 
    } else { 
    res.render('/401'); 
    return; 
    } 
}; 

app.js

var auth = require('./lib/auth'); 
... 
app.get('/item/:itemid', auth.checkPerm, routes.item.get); 

像上面的線最終路由處理面前可以疊加中間件。它必須具有相同的函數簽名並調用next();

+0

有沒有辦法在'next()'例程中傳遞數據? – Alan

+1

嗯...你可以,但我會保持簽名相同。我通常設置'res.locals.foo = foo;'如果我想將數據傳遞給中間件鏈。 – chovy

+0

哦,是的,它是javacsript。您可以添加到對象。 – Alan

2

如果我沒有理解這個問題,你知道:

// This is too general 
app.use(myAuthMiddleware()); 

而且大家都知道,你可以手動添加到某些網址的處理程序:

app.get('/user/profile/edit', myAuthMiddleware(), function(req,res){ 
    /* handle stuff */ }); 
// but doing this on all your routes is too much work. 

你可能不知道約express' mounting feature

// Matches everything under /static/** Cool. 
app.use('/static', express.static(__dirname + '/public')); 

或者app.all()

// requireAuthentication can call next() and let a more specific 
// route handle the non-auth "meat" of the request when it's done. 
app.all('/api/*', requireAuthentication); 
+0

好吧,這很酷。 – Alan