Question

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!

Was it helpful?

Solution

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')

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top