Recommand · December 8, 2021 0

Cant´t get cookie – Express

I created a server with express and have some get/post routes.

In the login page, I have a page that shows the form to login:

    app.get("/login", (req, res) => {
  res.send(`<h1>Iniciar sesión</h1>
  <form method='post' action='/login'>
    <input type='email' name='email' placeholder='Email' required />
    <input type='password' name='password' placeholder='Contraseña' required />
    <input type='submit' value='Ingresar' />
  </form>
  <a href='/register'>Registrarse</a`);
});

Then I have a Post method in which I set the cookies:

    app.post("/login", (req, res) => {
  const { email, password } = req.body;

  const user = users.filter(
    (e) => e.email === email && e.password === password
  );

  if (user.length >= 1) {
    res.cookie("userId", user.id);
    res.cookie("password", user.password);
    res.redirect("/home");
  } else {
    console.log("contraseña incorrecta");
    res.redirect("/login");
  }
});

The problem is that when I go to this route, the id variable is empty. In other words, I can´t acces to the cookie:

app.get("/home", (req, res) => {
  const id = req.cookies.userId;
  console.log(id); //this is undefined
  const user = users.filter((u) => u.id === id);
  //console.log(user);

  res.send(`
    <h1>Bienvenido ${user.name}</h1>
    <h4>${user.email}</h4>
    <a href='/'>Inicio</a>
  `);
});

Advices?