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

后端 未结 1 462
执笔经年
执笔经年 2021-01-31 20:04

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 var

1条回答
  •  有刺的猬
    2021-01-31 20:43

    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.

    0 讨论(0)
提交回复
热议问题