首页 > 解决方案 > 如何让 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) => {
    //....
}))

标签: node.jsexpressparameterscallbackmiddleware

解决方案


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

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

推荐阅读