November 2018
Beginner
502 pages
10h 22m
English
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": ...Read now
Unlock full access