JS Web APIsLesson #180

JavaScript Fetch API

The Fetch API interface lets you download (fetch) data from a web server.

The Fetch API interface lets you download (fetch) data from a web server.

await fetch() is the modern API for fetching data from an HTTP server.

XMLHttpRequest() was the old legacy API for fetching data from an HTTP server.

Share

What is Fetch API

JavaScript Fetch API is a modern browser interface used to make asynchronous network requests to web servers.

Fetch is an easier and more powerful replacement for the older XMLHttpRequest object.

Fetch is uses standard JavaScript Promises for cleaner asynchronous code.


Fetching a Text File

The simplest way to demonstrate fetch() is to download a text file.

Examples

Example Code

javascript
Try it Yourself
// Fetch a file

fetch(file)

  .then(function(response) {

      return response.text();

  })

  .then(function(data) {

    myDisplayer(data);

  });
Note that .then() expects a function as its argument, so you must write .then(...), not .then {...}.

Using an Asynchronous Function

Example Code

javascript
Try it Yourself
// Async function to fetch a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(await response.text());

}
Learn More... > Learn more about fetch() and asynchronous programming: > Asynchronous Fetch.

The Response Object

The fetch() method returns a Promise that resolves to a Response object.

The Response object contains information (properties) about the server response.

PropertyDescription
okTrue if the request succeeded
statusThe HTTP status code
statusTextThe HTTP status message
urlThe HTTP url address

Example

Example Code

javascript
Try it Yourself
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response);

}

The ok Property

Example

Example Code

javascript
Try it Yourself
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.ok);

}

The status Property

Example

Example Code

javascript
Try it Yourself
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.status);

}

The url Property

Example

Example Code

javascript
Try it Yourself
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.url);

}

Asynchrounous Output

JavaScript can continue running while waiting for the server to respond.

Example

Example Code

javascript
Try it Yourself
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.url);

}

loadText("fetch.txt");

myDisplayer("JavaScript continues.");
Note > "JavaScript continues." is displayed first. > It is displayed while loadText() waits for fetch() to resolve.

Response Object Methods

The Response object has methods to read the server response.

MethodDescription
text()Reads the response as text
json()Reads the response as JSON
blob()Reads the response as binary data
bytes()Reads the response as bytes
arrayBuffer()Reads the response as an ArrayBuffer
Learn More... > Learn how to use fetch() to request JSON files: > JSON Fetch Tutorial.

Checking for HTTP Errors

fetch() resolves when the server responds.

A common beginner mistake is expecting fetch() to fail on Http errors.

An HTTP error such as 404 Not Found does not reject the Promise.

Fetch only rejects on network errors.

A 404 response is not a rejected promise.

You should always check the ok property.

Example

Example Code

javascript
Try it Yourself
async function loadText(file) {

  const response = await fetch(file);

  if (!response.ok) {

    myDisplayer(response.status + " " + response.statusText);

    return;

  }

  myDisplayer(await response.text());

}
Note > Most fetch errors are not JavaScript errors. > They are most often path and response problems. > If fetch is not working, check the console. > Then check the Network tab. > Is the file name correct? > Is the file path correct? > Is the status code 200?

Fetch API vs. XMLHttpRequest (XHR)

FeatureFetchXHR
SyntaxPromise-basedCallback-based
Error HandlingRejects on network failureNeeds manual checking
StreamsSupports streamsDoes not support streams

Interactive Code Examples

Examples

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Fetch a file

fetch(file)

  .then(function(response) {

      return response.text();

  })

  .then(function(data) {

    myDisplayer(data);

  });

Using an Asynchronous Function

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Async function to fetch a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(await response.text());

}

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response);

}

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.ok);

}

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.status);

}

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Async function to download a file

async function loadText(file) {

  const response = await fetch(file);

  myDisplayer(response.url);

}