问题描述
我真的很困惑,因为我不知道什么时候我应该使用 app.locals
和 res.locals
他们怎么样?实际上我想知道 app.locals
和 res.locals
生命周期。例如,我应该在哪里保存我的用户(经过身份验证的用户)的详细信息(用户名,角色等)?在 app.locals
或 res.locals
?
感谢提前的怪胎。
您可以将 app.locals
全球化您可能想要存储在 app.locals
中的一些事例:URL助手,应用程序级常量。你应该把你想要的东西放在每一个视图中。
res.locals
仅存储数据特定响应(响应特定请求)。例如,GET / something将创建一个新的res.locals,通过所有的中间件通过响应/ something。这里适当的信息是像您的问题的验证用户详细信息。
生命周期看起来像这样,你的职责是大胆的(其他一切都是通过express完成的):
- 应用被创建(var app = express();)
- 创建app.locals
- 请求到达
- 根据该请求创建res.locals
- 您将内容添加到res.locals中,如用户角色(res。 locals.role ='admin';)
- 您对请求进行响应(res.render('some / view');)
- res.locals为该请求是垃圾回收,已经
- 只要应用程序存在,app.locals将继续存在
I really confused by app.locals
and res.locals
because I don't know WHEN should I use them and how? And actually I want to know the app.locals
and res.locals
life cycle.
For example where should I save my user (authenticated user) details (username, roles etc.)? In app.locals
or res.locals
?
Thanks in advance geeks.
You can consider app.locals
to be global. Some examples of things you might want to store in app.locals
: URL helpers, application-level constants. You should put anything here that you want accessible in every single view.
res.locals
stores data only for a particular response (which responds to a particular request). For example, GET /something will create a new res.locals that gets passed through all the middleware responding to '/something.' Appropriate information here is stuff like authenticated user details from your question.
The lifecycle looks like this, where your responsibilities are bold (everything else is done for you by express):
- app is created (var app = express();)
- app.locals is created
- request arrives
- res.locals is created for that request
- you add things to res.locals like user roles (res.locals.role = 'admin';)
- you serve a response to the request (res.render('some/view');)
- res.locals for that request is garbage collected, gone
- app.locals continues to exist as long as the app exists
这篇关于app.locals和res.locals生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!