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!
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.
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.
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.
The res. status() function set the HTTP status for the response. It is a chainable alias of Node's response.
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With