Generally to handle logins with express you'd use something like passport's local strategy, which attaches a user object to the request object (req.user
) for you for each route. I don't know that what you're trying will work in a larger context -- you'd need some kind of session-based middleware like express-session at the very least, so you can attach variables per session (I think it gives you req.session
). By default, express has the capability to store information for one request/response cycle (res.locals
) or for the entire instance of the app (i.e. for all users) (app.locals
).
As far as getting data into views, you would use res.render
with something like EJS, pug, or another view engine. For example, if in your route, you had something like:
route.get('/', (req, res) => {
res.render('template', { username: 'yourname' })
}
you can refer to that in your ejs template like so:
<h1>Hello, <%= username %>!</h1>
which will get sent back as this:
<h1>Hello, yourname!</h1>
So, to answer your question:
- You would use
res.render
to get variables & data into your views
- You don't share data across routes by default except app-level data that applies to all users, which can be set on
app.locals
- You can use authentication middleware like passport and session middleware like express-session to keep track of user information across routes per session.
Hope this helps! Good luck with express!