Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

node.js - app.locals and res.locals life cycle

I'm 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...