Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

node.js - req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...