node.js - 如何让 ExpressJS 中间件接受参数
问题描述
我想要得到的是添加一个统一的处理来控制不同资源的访问。非常感谢 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) => {
//....
}))
解决方案
您只需要编写一个返回中间件的函数:
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
});
推荐阅读
- powershell - 如何将新数据插入现有文件?
- google-chrome-extension - 使用 chrome.windows.create() 在 PWA 模式下启动一个窗口
- reactjs - 什么是“来自客户端的代码拆分代码”?
- aws-lambda - 异步 Lambda 函数在调用 DynamoDB 时返回 null
- azure-traffic-manager - 此配置文件不允许端点目标类型“域名”
- html - 页面加载动画中的 SVG 图像未从初始位置开始
- python - 使用python从csv生成大数组的热图
- google-app-engine - 当写入不在事务中时,Google App Engine 实体组是否被锁定
- macos - 用分隔符拆分大文件 - 内存不足
- arrays - Spring Cloud Open Feign:ByteArrayResource 的解码器