我想获得的是添加一个统一的处理程序来控制对不同资源的访问。 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
});