【问题标题】:Providing Custom Params In Express Middleware在 Express 中间件中提供自定义参数
【发布时间】:2016-08-17 19:09:17
【问题描述】:

我的 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) {} 会起作用,但我不明白如何包含我自己的参数。

【问题讨论】:

  • 什么参数?它们与传递给 http 请求的不同吗? (我的意思是查询参数等)

标签: javascript node.js function express middleware


【解决方案1】:

您的函数requirePermissions 应该返回另一个函数,该函数将是实际的中间件:

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
      }
    }
  }
}

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

    • 添加了.bind() 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2021-09-14
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多