在我的ExpressJS应用程序中,我的几个网址处理程序具有以下逻辑:
有没有办法通过ConnectJS或ExpressJS为某些网址处理程序插入预处理程序?
我知道我可以在全局范围内为所有处理程序执行此操作(我会根据IE的破坏XDR插入缺少的标头)。
但是,我可以为一部分处理程序执行此操作吗?
答案 0 :(得分: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();
答案 1 :(得分: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'));
// 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);