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

时间:2012-11-14 20:56:12

标签: node.js express connect

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

  1. 查看用户是否有权访问资源
  2. 如果是,请继续
  3. 否则,重定向到主处理程序。
  4. 有没有办法通过ConnectJS或ExpressJS为某些网址处理程序插入预处理程序?

    我知道我可以在全局范围内为所有处理程序执行此操作(我会根据IE的破坏XDR插入缺少的标头)。

    但是,我可以为一部分处理程序执行此操作吗?

2 个答案:

答案 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'));

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);