在我的 ExpressJS 应用程序中,我的几个 urls 处理程序具有以下逻辑:
- 查看用户是否有权访问资源
- 如果是,请继续
- 否则,重定向到主处理程序。
有没有办法通过 ConnectJS 或 ExpressJS 为某些 url 处理程序插入预处理程序?
我知道我可以在全局范围内为所有处理程序执行此操作(由于 IE 损坏的 XDR,我这样做是为了插入丢失的标头)。
但是,我可以为一部分处理程序执行此操作吗?
I do something like this:
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);
You can stack middleware before your final route handler like the above line has. It has to have same function signature and call next();
如果我正确理解了这个问题,您就知道:
// This is too general
app.use(myAuthMiddleware());
而且您知道您可以手动将其添加到某些 url-handlers:
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'));
// 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);