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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…