I use fetch() to post json data as below
var data = {
name: this.state.name,
password: this.state.password
}
fetch('http://localhost:3001/register/paitent', {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
I always get {} in request.body in my express server router, and I figure out the problem is in sending request, it's always 'text/plain'. Why this happens?

You set the mode to no-cors.
Setting the Content-Type to application/json requires permission from CORS…
The only allowed values for the Content-Type header [without triggering a preflight CORS request] are:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
— mdn
…which you told fetch not to ask for. Since you don't ask for permission, you don't get permission, so fetch reverts to text/plain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With