在我的 ExpressJS 应用程序中,我的几个 url 处理程序具有以下逻辑:
有没有办法通过 ConnectJS 或 ExpressJS 为某些 url 处理程序插入预处理程序?
我知道我可以在全局范围内为所有处理程序执行此操作(我这样做是为了插入由于 IE 损坏的 XDR 而丢失的标头)。
但是,我可以对处理程序的子集执行此操作吗?
我做了这样的事情:
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();
如果我正确理解这个问题,你知道:
// This is too general
app.use(myAuthMiddleware());
您知道您可以手动将其添加到某些 url 处理程序中:
app.get('/user/profile/edit', myAuthMiddleware(), function(req,res){
/* handle stuff */ });
// but doing this on all your routes is too much work.
您可能不知道的express'安装功能:
// 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);