【问题标题】:How to make ExpressJS middleware to accept parameters如何让 ExpressJS 中间件接受参数
【发布时间】:2019-11-05 09:19:23
【问题描述】:

我想得到的是添加一个统一的处理来控制不同资源的访问。非常感谢 accessControlMiddlewareA 或 accessControlMiddlewareB 样式!

router.post('/pathA', accessControlMiddlewareA("sectionA", req, res, next) => {
    //....
})
router.post('/pathB', accessControlMiddlewareA("sectionB", req, res, next) => {
    //....
})

或者,

router.post('/pathA', accessControlMiddlewareB("sectionA", (req, res, next) => {
    //....
}))
router.post('/pathB', accessControlMiddlewareB("sectionB", (req, res, next) => {
    //....
}))

【问题讨论】:

标签: node.js express parameters callback middleware


【解决方案1】:

你只需要写一个返回中间件的函数:

function accessControlMiddlewareA ( section ) {
    // now we return the actual middleware:
    return (req, res, next) {
        // use `section` in here
    }
}

那么你可以这样使用它:

router.post('/pathA', accessControlMiddlewareA("sectionA"));

如果您需要在中间件之后进行一些后期处理,只需添加另一个匿名中间件即可:

router.post('/pathA', accessControlMiddlewareA("sectionA"));
router.post('/pathA', (req, res, next) => {
    // additional logic here
});

或更短的版本:

// same as the code above:
router.post('/pathA', accessControlMiddlewareA("sectionA"), (req, res, next) => {
    // additional logic here
});

【讨论】:

  • 您好,这个问题已经在几个问题中提出并回答了,所以最好将此问题标记为重复。
猜你喜欢
  • 2012-09-26
  • 2012-10-22
  • 2015-04-10
  • 1970-01-01
  • 2021-10-29
  • 2015-07-24
  • 1970-01-01
  • 2020-05-15
相关资源
最近更新 更多