在 Express 中间件中提供自定义参数

Providing Custom Params In Express Middleware

我的 Node.js 应用程序有问题。简而言之,我想将自定义参数传递到我的中间件函数中,而不仅仅是 reqresnext.

中间件文件:

var DB = require('./DB.js');

function requirePermissions(e) { 
    console.log('nope')
}

module.exports = requirePermissions;

路线:

router.post('/posts', requirePermissions('post_creation'), function(req, res)       {
  var   o       = req.body,
      title   = o.post.title,
      content = o.post.content;

  res.send('made it');
});

我已经确认使用函数 requirePermissions(req, res, next) {} 会起作用,但我不明白如何包含我自己的参数。

您的函数 requirePermissions 应该 return 另一个函数,它将成为实际的中间件:

function requirePermissions(e) {
  if (e === 'post_creation') {
    return function(req, res, next) {
      // the actual middleware
    }
  } else if (e === 'something_else') {
    return function(req, res, next) {
      // do something else
    }
  }
}

你也可以这样做:

function requirePermissions(e) {
  return function(req, res, next) {
    if ('session' in req) {
      if (e === 'post_creation') {
        // do something
      } else if (e === 'something_else') {
        // do something else
      }
    }
  }
}

您可以只为您的中间件创建一个匿名函数,让您可以使用一些额外的参数调用您的实际函数:

router.post('/posts', function(req, res, next) {
      requirePermissions('post_creation', req, res, next);
   }, function(req, res) {
      var o   = req.body,
      title   = o.post.title,
      content = o.post.content;

      res.send('made it');
});

或者,您可以使用 .bind() 预先添加参数:

router.post('/posts', requirePermissions.bind('post_creation'), function(req, res) {
      var o   = req.body,
      title   = o.post.title,
      content = o.post.content;

      res.send('made it');
});

这将使用四个参数调用您的 requirePermissions() 函数,如下所示:

requirePermissions('post_creation', req, res, next)