2012-11-14 96 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