gpt4 book ai didi

node.js - Express 中间件中的 req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals

转载 作者:IT老高 更新时间:2023-10-28 21:52:53 28 4
gpt4 key购买 nike

问了一些类似的问题,但我的问题是,如果我想传播不同路由中间件的中间结果,最好的方法是什么?

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 属性初始化为空对象。

另外,也可以设置 res.mydata 或 req.mydata 属性?

理论上,app.locals 也可以用于通过不同的中间件传递这些数据,因为它会在中间件之间持续存在,但这与 app.locals 的传统用法相反。它更多地用于特定于应用程序的数据。还需要在请求-响应周期结束时清除该数据,以便可以将相同的变量用于下一个请求。

通过中间件传播中间结果的最佳和标准方式是什么?

最佳答案

正如您所提到的,req.localsres.locals 甚至您自己定义的键 res.userData 都可以使用。但是,当使用 Express 的 View 引擎时,您可以在中间件的 res.locals 上设置中间数据,这些数据将在您的 View 中可用(参见 this post )。通常的做法是在 req.locals 上的中间件内部设置中间数据,以避免覆盖 res.locals 中的 View 数据,尽管这没有正式记录。

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.

Source: http://expressjs.com/en/api.html#res.locals

关于node.js - Express 中间件中的 req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451053/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com