Categories
JavaScript Answers

How to set the content-type of request header when using Fetch API with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *