fetch()
is the modern way of sending requests over HTTP.
let promise = fetch(url, [options])
- The browser starts the request right away and returns a
promise
.
- The
promise
resolves with an object of the built-in Response class as soon as the server responds with headers.
- So we can check HTTP status, to see whether it is successful or not, check headers, but don’t have the body yet.
- The promise rejects if the
fetch
was unable to make HTTP-request, e.g. network problems, or there’s no such site. HTTP-errors, even such as 404 or 500, are considered a normal flow.
- We can see them in response properties:
ok
– boolean, true
if the HTTP status code is 200-299.
status
– HTTP status code.
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (see below)
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);
}
- To get the response body, we need to use an additional method call.
Response
provides multiple promise-based methods to access the body in various formats:
response.json()
– parse the response as JSON object,
response.text()
– return the response as text,
response.formData()
– return the response as FormData object (form/multipart encoding),
response.blob()
– return the response as Blob (binary data with type),
response.arrayBuffer()
– return the response as ArrayBuffer (pure binary data),
- Additionally,
response.body
is a ReadableStream object, it allows to read the body chunk-by-chunk.
- There’s a Map-like headers object in
response.headers
.
- We can get individual headers or iterate over them:
let response = await fetch('<https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits>');
console.log(response.headers.get('Content-Type')); // application/json; charset=utf-8
for (let [key, value] of response.headers) {
console.log(`${key} = ${value}`);
}
- To set a header, we can use the headers option, like this:
let response = fetch(protectedUrl, {
headers: {
Authentication: 'abcdef'
}
});
- To make a
POST
request, or a request with another method, we need to use fetch
options:
method
– HTTP-method, e.g. POST
,
body
– one of:
- A string (e.g. JSON),
FormData
object, to submit the data as form/multipart
,
Blob
/BufferSource
to send binary data,
- URLSearchParams, to submit the data as
x-www-form-urlencoded
, rarely used.
let user = {
name: 'John',
surname: 'Smith'
};
let response = await fetch('/article/fetch-basics/post/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(user)
});
let result = await response.json();
alert(result.message);