William Jones
William Jones

Reputation: 1129

How do I pass data from app.post to app.get on different pages?

In my app.js file, I am trying to pass the username from a form on the login page to the game page. I've got the data in req.body.username in app.post('/login'), but how should I pass this to app.get('/game')?

I considered making a global variable outside of the functions and then changing this in app.post('/login'), but that doesn't seem like a good way of doing things.

// Login
app.get('/login', (req, res) => {
    res.render('pages/login');
});

app.post('/login', (req, res) => {
    console.log(req.body.username)
});

// Game
app.get('/game/:name', (req, res) => {
    res.render('pages/game', {
        user: req.params.name
    });
});

app.listen(3000);

This is what my form looks like (login.ejs):

<main class="container-fluid">
  <h1>Login Page</h1>
  <form action="#" method="post">
      <p>Name:</p>
      Username: <input type="text" name="username" />
      <input type="submit" value="submit" />
  </form>
</main>

I'd also like the form to send the user to the game page when it's submitted. I tried changing action="#" to action="game", but that gave me an error - Cannot POST /game.

Thanks in advance for any help.

Upvotes: 0

Views: 822

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20934

Here is an example how one might do this. You'll need the cookie-parser package to read out the cookie from the request headers.

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

When a user hits the /login page, you'll want to set a cookie based on the user name. The name of the cookie could be anything you want. After setting the cookie, redirect to the /game endpoint.

app.post('/login', (req, res) => {
  res.cookie('current-user', req.body.username);
  res.redirect('/game');
});

Now we have a cookie stored with the data from the /login page, we can read it on any other endpoint. Because of the cookie-parser middleware we should now have access to req.cookie, which holds an object with all the cookie key-values pairs. Check if the cookie we just set exists and render the page with the user passed to the render function.

app.get('/game', (req, res) => {
  const cookies = req.cookies;
  const currentUser = cookies['current-user'];

  if (currentUser) {
    res.render('pages/game', {
      user: currentUser
    });
  } else {
    res.render('pages/game');
  }
});

Upvotes: 2

Related Questions