Fetch definition

Description

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.

It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

This kind of functionality was previously achieved using XMLHttpRequest.

Fetch provides a better alternative that can be easily used by other technologies such as Service Workers.

Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.

The fetch specification differs from jQuery.ajax() in three main ways :

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

  • fetch() won’t receive cross-site cookies. You can’t establish a cross site session using fetch(). Set-Cookie headers from other sites are silently ignored.

  • fetch() won’t send cookies, unless you set the credentials init option. Since Aug 25, 2017: The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)

An other mozilla definition

The Fetch API is basically a modern replacement for XHR; it was introduced in browsers recently to make asynchronous HTTP requests easier to do in JavaScript, both for developers and other APIs that build on top of Fetch.

Note

XMLHttpRequest (which is frequently abbreviated to XHR) is a fairly old technology now — it was invented by Microsoft in the late ’90s, and has been standardized across browsers for quite a long time.

Définition en français

L’API Fetch fournit une interface JavaScript pour l’accès et la manipulation des parties de la pipeline HTTP, comme les requêtes et les réponses.

Cela fournit aussi une méthode globale fetch() qui procure un moyen facile et logique de récupérer des ressources à travers le réseau de manière asynchrone.

Ce genre de fonctionnalité était auparavant réalisé avec XMLHttpRequest.

Fetch fournit une meilleure alternative qui peut être utilisée facilement par d’autres technologies comme Service Workers.

Fetch fournit aussi un endroit unique et logique pour la définition d’autres concepts liés à HTTP comme CORS et les extensions d’HTTP.

The Fetch API

Learn all about the Fetch API, the modern approach to asynchronous network requests which uses Promises as a building block.

Introduction to the Fetch API

Since IE5 was released in 1998, we’ve had the option to make asynchronous network calls in the browser using XMLHttpRequest (XHR).

Quite a few years after this, GMail and other rich apps made heavy use of it, and made the approach so popular that it had to have a name: AJAX.

Working directly with the XMLHttpRequest has always been a pain and it was almost always abstracted by some library, in particular jQuery has its own helper functions built around it:

  • jQuery.ajax()

  • jQuery.get()

  • jQuery.post()

and so on.

They had a huge impact on making this more accessible in particular with regards to making sure all worked on older browsers as well.

The Fetch API, has been standardized as a modern approach to asynchronous network requests, and uses Promises as a building block.

Using Fetch

Starting to use Fetch for GET requests is very simple:

fetch('/file.json')

and you’re already using it: fetch is going to make an HTTP request to get the file.json resource on the same domain.

As you can see, the fetch function is available in the global window scope .

Now let’s make this a bit more useful, let’s actually see what the content of the file is:

fetch('./file.json')
  .then(response => response.json())
  .then(data => console.log(data))

Calling fetch() returns a promise. We can then wait for the promise to resolve by passing a handler with the then() method of the promise.

That handler receives the return value of the fetch promise, a Response object .

Body content

A response has a body, accessible using several methods:

text() returns the body as a string json() returns the body as a JSON-parsed object blob() returns the body as a Blob object formData() returns the body as a FormData object arrayBuffer() returns the body as an ArrayBuffer object

fetch('./file.json')
  .then(response => response.text())
  .then(body => console.log(body))

ES2017 async functions

The same can be written using the ES2017 async functions

;(async () => {
  const response = await fetch('./file.json')
  const data = await response.json()
  console.log(data)
})()

How to cancel a fetch request

For a few years after fetch was introduced, there was no way to abort a request once opened.

Now we can, thanks to the introduction of AbortController and AbortSignal, a generic API to notify abort events

You integrate this API by passing a signal as a fetch parameter:

const controller = new AbortController()
const signal = controller.signal

fetch('./file.json', { signal })

You can set a timeout that fires an abort event 5 seconds after the fetch request has started, to cancel it:

setTimeout(() => controller.abort(), 5 * 1000)

Conveniently, if the fetch already returned, calling abort() won’t cause any error.

When an abort signal occurs, fetch will reject the promise with a DOMException named AbortError:

fetch('./file.json', { signal })
  .then(response => response.text())
  .then(text => console.log(text))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.error('Fetch aborted')
    } else {
      console.error('Another error', err)
    }
  })

Looking for more ?

Working with network is hard, right? You might find that the Axios JavaScript library might be a better fit for your needs with some additional features built upon Fetch.

Check it out!