Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS: What is the difference between app.local and res.local?

I'm trying to learn Express and in my app I have middleware that passes the session object from the Request object to my Response object so that I can access it in my views:

app.use((req, res, next) ->
  res.locals.session = req.session
  next()
)

But app.locals is available to the view as well right? So is it the same if I do app.locals.session = req.session? Is there a convention for the types of things app.locals and res.locals are used for?

I was also confused on what the difference is between res.render() and res.redirect()? When should each be used?

Thanks for reading. Any help related to Express is appreciated!

like image 665
aeyang Avatar asked Sep 25 '12 20:09

aeyang


People also ask

What is RES local Express?

The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.

What is the difference between app use and app get in ExpressJS?

app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

What is app locals in NodeJS?

The app. locals object defines the properties that are local variables inside an application. Once the value of app. locals property is set, it persists throughout the life of the application.

What is RES status?

The res. status() function set the HTTP status for the response. It is a chainable alias of Node's response.


2 Answers

app.locals and res.locals can be used in different contexts.

res.locals is for when you handle the route where you have a res object, you won't have an app object there and vice-versa for app.locals.

also res.render will render the page, to handle the request. res.redirect will redirect them to a different page.

For example if they try to access /account without logging in, you could flash a message and use res.redirect('/login')

like image 196
chovy Avatar answered Oct 21 '22 03:10

chovy


To illustrate this further, I remember viewing a flowchart which shows how express renders variables found inside a template. This is from "Node.js In Action." I recommend reading the chapter discussing Express.js.

enter image description here

like image 29
Michael Avatar answered Oct 21 '22 05:10

Michael