ConnectJS/ExpressJS url 处理程序的通用预处理程序?

问题描述 投票:0回答:2

在我的 ExpressJS 应用程序中,我的几个 url 处理程序具有以下逻辑:

  1. 查看用户是否有访问资源的权限
  2. 如果是这样,请继续
  3. 否则,重定向到主处理程序。

有没有办法通过 ConnectJS 或 ExpressJS 为某些 url 处理程序插入预处理程序?

我知道我可以在全局范围内为所有处理程序执行此操作(我这样做是为了插入由于 IE 损坏的 XDR 而丢失的标头)。

但是,我可以对处理程序的子集执行此操作吗?

node.js express node.js-connect
2个回答
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();


2
投票

如果我正确理解这个问题,你知道:

// 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);
© www.soinside.com 2019 - 2024. All rights reserved.