Fetch API
The Fetch API allows JavaScript to communicate with the server using HTTP requests and is a better replacement for the XMLHttpRequest class. Queries are executed by the fetch()
method, which returns Promise.
Syntaxβ
fetch(url, { options })
url
- URL for sending the request;options
- request parameters.
By specifying the fetch()
method without options
, you will receive a GET request that fetch data from the URL
.
Parameters requestβ
The second argument to {options}
accepts request parameters. Parameter list:
method
- request method (GET, POST, PUT, DELETE, HEAD);headers
- HTTP headers;body
- request body (used for method: POST / PUT);cache
- caching mode (default, reload, no-cache);mode
- request mode (cors, no-cors, same-origin);redirect
- specifies how to handle redirects (follow, error, manual);referrer
- request referrer;signal
- AbortSignal, interrupt request;credentials
- sending cookies along with the request - mit, same-origin.
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
mode: 'no-cors'
})
Receiving a responseβ
The fetch()
method returns Promise an object of the Response
class, which has the following properties:
status
- response code;statusText
- text message corresponding to the response code;ok
- a boolean value indicating the success of the response code (true: 200-299);headers
- an object with response headers, in which the key is the name of the header, and the key value is the value of the header corresponding to the key;url
- the URL to which the request was sent;body
- response data inReadableStream
formatbodyUsed
- Boolean value indicating data reading.
fetch('https://jsonplaceholder.typicode.com/users').then(response => console.log(response))
Response handlingβ
The transmitted data is in the format ReadableStream
. The following methods can be used to change the format:
text()
- converts the answer to a string;json()
- converts the response in JSON format;blob()
- converts the response to a Blob object;formData()
- the response is converted into a FormData instance;arrayBuffer()
- converts the response to an ArrayBuffer object.
An example of converting a response to JSON format.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data))
Error processingβ
We can find out whether fetch()
has completed with an error using the "status" and "ok" properties.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
console.log('Something went wrong ... Status:' + response.status)
} else {
return response.json()
}
})
.then(data => console.log(data))
With help .catch()
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error))
Request examplesβ
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data[0].name + ' and ' + data[2].name))
.catch(error => console.log(error))
The same, using the async / await
syntax, which we will get to know in more detail in the next article.
let response = await fetch('https://jsonplaceholder.typicode.com/users')
let data = await response.json()
console.log(data[0].name + ' and ' + data[2].name)
Problems?β
Write to Discord chat.
Questions:β
What does the fetch()
method return?
- Function
- Object
- Promise
Given only the URL parameter in fetch (), what request do we get?
POST
GET
PUT
What parameter are HTTP headers specified?
redirect
headers
credentials
What method should you use to convert the response to a string?
blob()
json()
text()
What does the ok
property mean for an object of class Response
?
- Response code
- Success of the response code
- Reading data from a request
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Linksβ
Contributors β¨β
Thanks goes to these wonderful people (emoji key):
IIo3iTiv | Dmitriy Vasilev π΅ | Resoner2005 π π¨ π | Navernoss π π π¨ |