问题描述
有一些类似的问题,但我的问题是,如果我想传播中间结果,我沿着不同的路由中间件,最好的方法是什么? app.use(f1); app.use(F2); app.use(F3);
函数f1(req,res,next){
//一些数据库查询被执行,我得到结果,说x1
res.locals.dbResults = {... };
next();
}
函数f2(req,res,next){
//更多根据req.locals.dbResults处理
res.locals.moreResults = {。 ...};
next();
}
...
我认为通过使用 req .locals可以通过不同的中间件获得相同的数据传播。此外,似乎请求和响应对象都在请求开始时将本地属性初始化为空对象。
另外,可以设置res.mydata或者req.mydata属性?
在理论上,app.locals也可以用于传递这些数据,通过不同的中间件,因为它将持续跨越中间件,但是与常规使用app.local相反。它更多地用于应用程序特定的数据。还有必要在请求 - 响应周期结束时清除数据,因此相同的变量可以用于下一个请求。
什么是通过中间件传播中间结果的最佳和标准方式?
正如您所提到的, req.locals
, res.locals
甚至你自己定义的键 res.userData
可以使用。除了命名,没有什么不同。话虽如此,但是我建议使用 res.locals
,因为这是在官方的Express.js文档中提到的唯一一个: p>
由于正式记录,所以使用 res.locals
属性的机会更少(向后兼容)。如果您选择自己的密钥,Express.js的将来版本总是有机会覆盖您的数据,因为它们恰好使用相同的密钥。使用 res.locals
时不会发生这种情况。这也使新人更容易理解您的代码,因为大多数项目使用 res.locals
来存储中间件数据。
There are some similar questions asked but my question is that if I want to propagate intermediate results that I get along the different routing middleware, what is the best way to do that?
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();
} ...
I think that I can get the same propagation of data through the different middleware by using req.locals. Also, it appears that the request and response objects both have the locals properties initialized to an empty object at the start of the request.
Also, one can set res.mydata or req.mydata properties too?
In theory, app.locals can also be used for passing this data along through the different middleware as it will persist across middlewares but that would be contrary to the conventional use of app.locals. It is used more for application specific data. It will also be necessary to clear that data at the end of the request-response cycle so the same variables can be used for the next request.
What is the optimal and standard way to propagate intermediate results through middleware?
As you mentioned, both req.locals
, res.locals
or even your own defined key res.userData
can be used. Apart from naming, there's no real difference. That being said, I would however recommend to use res.locals
as this is the only one mentioned in the official Express.js documentation:
Because it's officially documented, there's less chance of the res.locals
property ever being used for anything else (backwards compatibility). If you pick out your own key, there's always a chance future versions of Express.js will overwrite your data because they happen to use the same key. This won't happen when using res.locals
. It also makes it easier for new people to understand your code as most projects use res.locals
to store middleware data.
这篇关于req.locals vs. res.locals vs. res.data vs. req.data vs. Express中间件中的app.locals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!