0

I'm reading the Express framework docs, making my basic login/redirect page routes. The following route accepts the submission:

app.post('/',function(req,res){
//console.log("USERNAME: "+req.body.username);
//console.log("PASSWORD: "+req.body.password);
res.redirect('/chat');
});

and this:

app.get('/chat', function(req, res){
    res.sendFile(__dirname + '/templates/chat.html');
    //console.log("request");
});

takes the user to a new page. How do I send context? Should I be using res.render()? Neither function seems to contain an option for data like {username:req.body.username}. How should data be passed between routes?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • What do you mean "send context"? You can use a server-side session (see express-session) or you can set a cookie and put some data in the cookie if you want to add some state to a given browser's requests. – jfriend00 Mar 20 '18 at 01:56
  • For temporal state of only the next request, you can also redirect to a URL containing query parameters. – jfriend00 Mar 20 '18 at 02:12

1 Answers1

0

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!

JSilv
  • 1,035
  • 12
  • 26