问题描述
问了一些类似的问题,但我的问题是,如果我想传播我在不同路由中间件中得到的中间结果,最好的方法是什么?
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();
}
// ...
我认为我可以通过使用 req.locals 通过不同的中间件获得相同的数据传播.此外,请求和响应对象似乎都在请求开始时将 locals 属性初始化为空对象.
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.
另外,也可以设置 res.mydata 或 req.mydata 属性吗?
Also, one can set res.mydata or req.mydata properties too?
理论上,app.locals 也可用于通过不同的中间件传递这些数据,因为它会跨中间件持续存在,但这与 app.locals 的传统用法相反.它更多地用于特定于应用程序的数据.还需要在请求-响应周期结束时清除该数据,以便可以将相同的变量用于下一个请求.
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.
通过中间件传播中间结果的最佳和标准方式是什么?
推荐答案
正如你提到的,req.locals
、res.locals
甚至你自己定义的键 res.userData
可以使用.但是,当在 Express 中使用视图引擎时,您可以在中间件中的 res.locals
上设置中间数据,并且该数据将在您的视图中可用(请参阅 这篇文章).通常的做法是在 req.locals
上的中间件内部设置中间数据以避免覆盖 res.locals
中的视图数据,尽管这没有正式记录.
As you mentioned, both req.locals
, res.locals
or even your own defined key res.userData
can be used. However, when using a view engine with Express, you can set intermediate data on res.locals
in your middleware, and that data will be available in your view (see this post). It is common practice to set intermediate data inside of middleware on req.locals
to avoid overwriting view data in res.locals
, though this is not officially documented.
res.locals包含作用域为请求的响应局部变量的对象,因此仅可用于呈现的视图在该请求/响应周期(如果有).否则,这属性与 app.locals
相同.
这个属性对于暴露请求级别的信息很有用,比如请求路径名、认证用户、用户设置等.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
来源:http://expressjs.com/en/api.html#res.当地人
这篇关于Express中间件中的req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!