如何在每个到公共函数的路由上注入一个唯一的键,而不在nodejs中向其传递参数route.js文件ATR中的



router.use('/route1', route1);
router.use('/route2', route2);
router.use('/route3', route3);

在路线中.js

router.get('/routeapi', (req, res) => {
formatterFunc()
.then((response) => res.send(response))
.catch((error) => res.status(error.status || 500).send(errorHandler(error)));
});
formatterFunc(){
commonFunc()
}

common.js

commonFunc(){
performOperation(uniqueKey);
}

每个api调用的头中都有不同的uniqueKey。如何在不将req作为formatterFunc中的参数的情况下将uniqueKey传递给commonFunc。是否有使用中间件之类的解决方案。

您可以截取请求中的标头,如下伪代码

代码执行将采取从左到右的方向

router.get('/routeapi',formatterFunc, (req, res) => {
.then((response) => res.send(response))
.catch((error) => res.status(error.status || 500).send(errorHandler(error)));
});
exports.formatterFunc=(req,res,next)=>{
req.headers['customHeaderName'] = 'customHeaderValue'; //unique-key
next();
}

希望,它能围绕你的问题给出一些扩展的想法

最新更新