Below is my frontend code i have to submit a post request from react.
const { name, email, message } = greeting;
const payload = {
name: name,
email: email,
message: message,
};
console.log(payload);
fetch('http://localhost:8080/greetings', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(payload),
})
.then(async function (res) {
let response = await res.json();
console.log(response);
})
.catch((err) => console.log(err));
Below is my express code for post
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/greetings', async (req, res) => {
const { name, email, message } = req.body;
console.log(req.body);
db();
const saveDocument = new Document({
name: name,
email: email,
message: message,
});
await saveDocument
.save()
.then((savedDoc) => {
res.send({ status: 200, mes: 'success', request: req.body });
})
.catch((e) => console.log(e));
});
I have tried to submit a post using postman and i was able to see data in my mongoDB. But from my frontend i always get an empty object in the request.body.
2
Answers
There’s 2 different types of commonly used
Content-Type
:application/x-www-form-urlencoded
application/json
In Postman, you have specified to use
application/x-www-form-urlencoded
instead ofapplication/json
, which is why there’s a mismatch between the behaviour in Postman andfetch
request in React.When you specified your request to use
application/json
, your Express server needs to be able to handle the parsing as well.In Express 4.16 and above, you can use the
express.json()
middleware to parse your request into a JSON object to be retrieved usingreq.body
,bodyParser
(orbody-parser
) is deprecated. An example is as follows:The
express.json()
is a middleware to parseContent-Type: application/json
, whereasexpress.urlencoded()
is used to parseContent-Type: application/x-www-form-urlencoded
In order to test sending
Content-Type: application/json
in Postman, you can follow the screenshot below:(Screenshot source: Send POST data via raw JSON with Postman)
The issue seens to be with parsing the incoming request body. You are using
bodyParser.urlencoded
middleware, but you need to usebodyParser.json()
middleware to parse JSON-encoded request bodies.You can fix this by including the
bodyParser.json()
middleware like so:Now, you should be able to properly parse the JSON payload from the React frontend instead of getting an empty object in
req.body
.