本文介绍了app.locals和res.locals生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑,因为我不知道什么时候我应该使用 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完成的):


  1. 应用被创建(var app = express();)

  2. 创建app.locals

  3. 请求到达

  4. 根据该请求创建res.locals

  5. 您将内容添加到res.locals中,如用户角色(res。 locals.role ='admin';)

  6. 您对请求进行响应(res.render('some / view');)

  7. res.locals为该请求是垃圾回收,已经

  8. 只要应用程序存在,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):

  1. app is created (var app = express();)
  2. app.locals is created
  3. request arrives
  4. res.locals is created for that request
  5. you add things to res.locals like user roles (res.locals.role = 'admin';)
  6. you serve a response to the request (res.render('some/view');)
  7. res.locals for that request is garbage collected, gone
  8. app.locals continues to exist as long as the app exists

这篇关于app.locals和res.locals生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 17:41