Receive Nodejs post form returns Undefined

Asked

Viewed 158 times

1

I am learning socket.io developing a chat and etc. What happens is that on the login page I am creating I am not being able to receive input data.

<!DOCTYPE html>
<html lang="pt-br">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <link rel="stylesheet" href="index.css">
</head>

<body>
  <div class="container">
    <div class="login">
      <h4>Login</h4>
      <form id="login" method="POST" action="/home">
        <input type="text" name="username" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit">Login</button>
      </form>
      <small>Ainda não tem uma conta?<a href="register.html">Clique aqui.</a></small>
    </div>
  </div>
</body>

</html>

And when I try to receive these values on my routes he returns me Undefined:

routes.post('/home', (req, res) => {
  const { username, password } = req.body;

  console.log(username + ": " + password)
  res.render('home.html')
})

On my server.js (which is the main file) I am passing the app.use(express.json()) and yet my only return I have on my terminal is:

undefined: undefined

1 answer

1


HTML forms do not send data in JSON format. They send us, by default, in Encoded URL format. Therefore, use middleware express.json() is, in your case, a error.

You must use the middleware do the parse of body in URL format Encoded. Thus:

app.use(express. urlencoded());

See the documentation to learn more.

You can also use both, if you are using both formats. But I believe that is not the case.

  • Thanks I’m still learning. I would never have imagined something like it. VLW

Browser other questions tagged

You are not signed in. Login or sign up in order to post.