I am new to using the fetch function and can't figure out why this fetch function wont change the headers. Specifically I can't seem to change the content-type to json making the API return a 415. I have tried with mode set to both 'cors' and 'no-cors' and neither seems to make the difference.
const fetchOptions: RequestInit = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
await fetch("https://localhost:44375/api/users/login", fetchOptions)
.then(response => {
console.log(response);
})
Here is a link to a picture of my Chrome console:
As you can see, it is content-type plain text while also being in cors mode.
The issue here was server side and not client side. My web api was not allowing the Content-Type header to be changed due to a pre-flight OPTIONS request from the browser. This was fixed by properly setting up the cors policy on the server side.
In my case I am writing a C# api and it was as simple as adding WithHeaders to my policy:
builder.Services.AddCors(options => options.AddPolicy(name: "DevOrigins",
builder =>
{
builder.WithOrigins("http://localhost:3000");
builder.WithHeaders("Content-Type");
})
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.