Express.js: app.locals vs res.locals vs req.session

僤鯓⒐⒋嵵緔 提交于 2019-12-03 05:55:24

问题


I'm trying to understand when it's best to use each of the following. Here is my rudimentary understanding:

app.locals -- good for storing global variables at the app level. all users/sessions will see the same values for these variables. the variables are available to all views.

res.locals -- good for storing variables for the specific request/response cycle. the variables are only available to the view associated with the response.

req.session -- good for storing variables associated with the unique user session (e.g., user name). these variables should be available to all views for the unique user/session.

The specific use case I have is as follows: A user runs query which retrieves data from mongodb. I now want the result of this query, which is a JSON array, available as a variable to ALL of the views (HTTP requests). What's the best way to "store" the result array so that each view can access it?


回答1:


I now want the result of this query, which is a json array, available as a variables to ALL of the views. What's the best way to "store" the result array so that each view can access it?

When you say "available to ALL of the views" I assume you mean across all HTTP requests. If that is the case then you need to be aware that HTTP is a stateless protocol and does not provide for this. You'll need to develop your own mechanism for this.

One way of doing this is by cacheing this information (the array) on the server and retrieve it on every request (for example, retrieve it from memory rather than from MongoDB). You'll store a session ID on the cookie and based on this ID fetch it from cache when another requests comes through. There are several cache tools available (e.g. redis, memcached, et cetera) that you can chose to store the information in memory.

You could also cookie this information (the array itself) in which case it will be send back and forth between the client and the server on every HTTP request and very likely won't be a very good idea unless the data is very small.



来源:https://stackoverflow.com/questions/15294941/express-js-app-locals-vs-res-locals-vs-req-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!