Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why content-type in header remains text/plain though I set it as application/json

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?

enter image description here

like image 902
Bing Lan Avatar asked Dec 14 '25 10:12

Bing Lan


1 Answers

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.

like image 71
Quentin Avatar answered Dec 15 '25 23:12

Quentin