req.locals vs. res.locals vs. res.data vs. req.data vs. Express 中间件中的 app.locals
req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware
有人提出了一些类似的问题,但我的问题是,如果我想传播通过不同的路由中间件获得的中间结果,最好的方法是什么?
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 通过不同的中间件获得相同的数据传播。此外,请求和响应对象似乎都在请求开始时将本地属性初始化为空对象。
此外,是否也可以设置 res.mydata 或 req.mydata 属性?
理论上,app.locals 也可用于通过不同的中间件传递此数据,因为它会跨中间件持续存在,但这与 app.locals 的常规用法相反。它更多地用于特定于应用程序的数据。还需要在请求-响应周期结束时清除该数据,以便下一个请求可以使用相同的变量。
通过中间件传播中间结果的最佳和标准方式是什么?
正如您提到的,req.locals
、res.locals
甚至您自己定义的键 res.userData
都可以使用。但是,当使用带有 Express 的视图引擎时,您可以在中间件中的 res.locals
上设置中间数据,并且该数据将在您的视图中可用(参见 this post)。通常的做法是在 req.locals
上的中间件内部设置中间数据以避免覆盖 res.locals
中的视图数据,尽管这没有正式记录。
res.locals
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered
during that request / response cycle (if any). Otherwise, this
property is identical to app.locals
.
This property is useful for exposing request-level information such as
the request path name, authenticated user, user settings, and so on.
有人提出了一些类似的问题,但我的问题是,如果我想传播通过不同的路由中间件获得的中间结果,最好的方法是什么?
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 通过不同的中间件获得相同的数据传播。此外,请求和响应对象似乎都在请求开始时将本地属性初始化为空对象。
此外,是否也可以设置 res.mydata 或 req.mydata 属性?
理论上,app.locals 也可用于通过不同的中间件传递此数据,因为它会跨中间件持续存在,但这与 app.locals 的常规用法相反。它更多地用于特定于应用程序的数据。还需要在请求-响应周期结束时清除该数据,以便下一个请求可以使用相同的变量。
通过中间件传播中间结果的最佳和标准方式是什么?
正如您提到的,req.locals
、res.locals
甚至您自己定义的键 res.userData
都可以使用。但是,当使用带有 Express 的视图引擎时,您可以在中间件中的 res.locals
上设置中间数据,并且该数据将在您的视图中可用(参见 this post)。通常的做法是在 req.locals
上的中间件内部设置中间数据以避免覆盖 res.locals
中的视图数据,尽管这没有正式记录。
res.locals An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to
app.locals
.This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.