Sometimes, we want to set the content-type of request header when using Fetch API with JavaScript.
In this article, we’ll look at how to set the content-type of request header when using Fetch API with JavaScript.
How to set the content-type of request header when using Fetch API with JavaScript?
To set the content-type of request header when using Fetch API with JavaScript, we can put the header in a Header
object.
For instance, we write
const options = {
method,
headers: new Headers({ "content-type": "application/json" }),
mode: "no-cors",
body: JSON.stringify(body),
};
await fetch(url, options);
to call fetch
to make a request to the url
with the request method
.
We set headers
to a Headers
object with the content-type
header set to 'application/json'
.
body
is the stringified request body JSON.
Conclusion
To set the content-type of request header when using Fetch API with JavaScript, we can put the header in a Header
object.