Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Content-Type in fetch request not working

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?

like image 787
u8y7541 Avatar asked Aug 12 '17 21:08

u8y7541


People also ask

How do I specify content-type in Fetch?

To set the content-type of request header when using Fetch API with JavaScript, we can put the header in a Header object. const options = { method, headers: new Headers({ "content-type": "application/json" }), mode: "no-cors", body: JSON. stringify(body), }; await fetch(url, options);

Does fetch allow Cors?

Supplying request options The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings: See fetch() for the full options available, and more details. Note that mode: "no-cors" only allows a limited set of headers in the request: Accept.


1 Answers

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).

like image 159
Quentin Avatar answered Sep 22 '22 08:09

Quentin