Body of the request (req.body) returning empty object when submitting form

Asked

Viewed 31 times

1

I have basically two files. HTML, so:

<form action="/result", method="POST">
  <input id="phrase" type="text" name="phrase" value="Processar frase" />
  <input type="submit" value="Processar!" />
</form>

And an Express app:

const express = require('express');

var app = express();

app.use(express.json());

app.post('/result', (req, res) => {
    res.json(req.body);
});

Basically, when I send any data by the form, the endpoint /result returns an empty object to req.body:

{}

Instead of returning the value passed in the form field, as I expected. I have tried several ways and seen many people talking about using the body-parser, however, I also saw that he is depreciated, for this reason I prefer not to use.

Why am I not receiving the data as expected?

1 answer

2


Are you using the middleware incorrect.

HTML forms, that is, the elements <form>, by default send the data submitted by the user in the body of the request with the Content-Type application/x-www-form-urlencoded. There are two other possible settings according to the attribute value enctype.

Now note that your application is using middleware express.json() that awaits the body of the request under the Content-Type application/json. HTML forms do not support this format.

So change the middleware for the appropriate amount you are sending. In that case, do:

app.use(express.urlencoded());

Be sure to consult the documentation that middleware.

Browser other questions tagged

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