Making a POST request with JSON body with fetch to a Node.js Express server
I tried to rewrite a POST request to a Node.js server from the deprecated package request
to the standard fetch API. I initially wrote this:
const username = 'some string';
const password = 'some string';
const response = await fetch(process.env.NEXT_PUBLIC_API_DOMAIN + 'signin', {
method: 'POST',
body: JSON.stringify({ username, password })
});
But on the Node.js side, request.body
would contain {}
. I did check that on the Node.js side, I had set up the json middleware to parse JSON from the body of POST requests.
After googling a bit, it turns out I was missing the header:
const response = await fetch(process.env.NEXT_PUBLIC_API_DOMAIN + 'signin', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: {"Content-Type": "application/json"}
});
After adding the header, Express parses request.body
correctly.