Skip to main content

Fetch API

@serverSerrverlesskiy

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.

Exchange

Syntax​

Book

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​

Option

The second argument to {options} accepts request parameters. Parameter list:

  1. method - request method (GET, POST, PUT, DELETE, HEAD);
  2. headers - HTTP headers;
  3. body - request body (used for method: POST / PUT);
  4. cache - caching mode (default, reload, no-cache);
  5. mode - request mode (cors, no-cors, same-origin);
  6. redirect - specifies how to handle redirects (follow, error, manual);
  7. referrer - request referrer;
  8. signal - AbortSignal, interrupt request;
  9. 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​

Bascketball

The fetch() method returnsπŸ”„ Promise an object of the Response class, which has the following properties:

  1. status - response code;
  2. statusText - text message πŸ“œ corresponding to the response code;
  3. ok - a boolean value indicating the success of the response code (true: 200-299);
  4. 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;
  5. url - the URL to which the request was sent;
  6. body - response data in ReadableStream format
  7. bodyUsed - Boolean value indicating data reading.
fetch('https://jsonplaceholder.typicode.com/users').then(response => console.log(response))

Response handling​

Download

The transmitted data is in the format ReadableStream. The following methods can be used to change the format:

  1. text() - converts the answer to a string;
  2. json() - converts the response in JSON format;
  3. blob() - converts the response to a Blob object;
  4. formData() - the response is converted into a FormData instance;
  5. 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​

Error

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​

Math

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?​

Problem

Write to Discord chat.

Questions:​

Question

What does the fetch() method return?

  1. Function
  2. Object
  3. Promise

Given only the URL parameter in fetch (), what request do we get?

  1. POST
  2. GET
  3. PUT

What parameter are HTTP headers specified?

  1. redirect
  2. headers
  3. credentials

What method should you use to convert the response to a string?

  1. blob()
  2. json()
  3. text()

What does the ok property mean for an object of class Response?

  1. Response code
  2. Success of the response code
  3. 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.

JS Camp

  1. Learn JavaScript
  2. MDN Web Docs
  3. JS Tutorial

Contributors βœ¨β€‹

Thanks goes to these wonderful people (emoji key):


IIo3iTiv

πŸ“–

Dmitriy Vasilev

πŸ’΅

Resoner2005

πŸ› 🎨 πŸ–‹

Navernoss

πŸ–‹ πŸ› 🎨

Become a Patron!