30

I am doing a remote fetch request to a server. The payload is in JSON format, so I want to change the Content-Type header to application/json. I have used the following code to do this:

let email = document.getElementById("email").value
let password = document.getElementById("password").value

const body = {"email":email, "password":password}
const headers = new Headers({
    "Content-Type": "application/json",
    "Content-Length": JSON.stringify(body).length
})
const options = {
    method: "POST",
    mode: "no-cors",
    headers: headers,
    body: JSON.stringify(body)
}
console.log(options)
const response = await fetch('http://xx.xx.xx.xxx/login', options)
const json = await response.json()
console.log(json)

However, in the Chrome developer tools console, the Content-Type header of the request is still text/plain;charset=UTF-8. What am I doing wrong?

u8y7541
  • 548
  • 2
  • 8
  • 13
  • Possible duplicate of [Fetch: post json data, application/json change to text/plain](https://stackoverflow.com/questions/39689386/fetch-post-json-data-application-json-change-to-text-plain) – CodeZombie Feb 16 '18 at 10:48

1 Answers1

53

Overriding the Content-Type request header is not allowed for no-cors requests.

Change the mode to cors.

(You won't be able to read the response without doing that either).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 8
    Which is, of course, utterly useless if you have an endpoint which doesn't CORS. :-( – Phil Apr 02 '18 at 04:37
  • @Quentin yes. Just means extra stuff required to work around the problem. eg, proxy the endpoint, modifying headers. Or change the endpoint so that it does CORS. I elected to proxy the endpoint rather than touch that old legacy code. :-) – Phil Apr 03 '18 at 03:21
  • 8
    [Here is the relevant section of the documentation for fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options), that states that when using `no-cors` mode, you cannot set a value of `application/json` for the `Content-Type` header. – Wyck Dec 26 '20 at 16:42