Fetch: How to use Fetch

The Fetch API provides an easy way to perform networking in JavaScript.

Starting to use Fetch for GET requests is very simple:


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:

  .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.

We’ll see this object in detail in the next section.

Lessons in this unit:

0: Introduction
1: ▶︎ How to use Fetch
2: Catching errors in network requests
3: The Response object
4: Getting the body content
5: The Request object
6: Request headers
7: POST requests