Request HTTP headers

Very often, we need to include HTTP headers in the request. We can specify these in the options object in a headers property:


fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "bearer some-bearer-token"
},
body: JSON.stringify({
title: "Interesting post",
body: "This is an interesting post about ...",
userId: 1
})
})
.then(response => {
console.log(response.status);
return response.json();
})
.then(data => console.log(data));

Request headers can be used in this way for any HTTP method and not just an HTTP POST. For example, we can use this for a GET request as follows:

fetch("https://jsonplaceholder.typicode.com/posts/1", {
headers: {
"Content-Type": "application/json",
Authorization: "bearer some-bearer-token"
}
}).then(...);

So, that's how to use fetch to post data to a REST API. In the next section, we'll look at changing data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.162.37