有一些类似的问题,但我的问题是,如果我想传播我得到的不同路由中间件的中间结果,那么最好的方法是什么?
app.use(f1); app.use(f2); app.use(f3);
function f1(req,res,next) {
//some database queries are executed and I get results, say x1
res.locals.dbResults = {...};
next();
}
function f2(req,res,next) {
// more processing based upon req.locals.dbResults
res.locals.moreResults = {....};
next();
}
// ...
Run Code Online (Sandbox Code Playgroud)
我认为通过使用req .locals ,我可以通过不同的中间件获得相同的数据传播.此外,似乎请求和响应对象都在请求开始时将locals属性初始化为空对象.
另外,还可以设置res.mydata或req.mydata属性吗?
从理论上讲,app.locals也可用于通过不同的中间件传递这些数据,因为它将持续穿过中间件,但这与app.locals的传统使用相反.它更多地用于特定于应用程序的数据.还需要在请求 - 响应周期结束时清除该数据,以便相同的变量可用于下一个请求.
通过中间件传播中间结果的最佳和标准方法是什么?