Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

JS Tutorial

JS Home JS Introduction JS Where To JS Output JS Syntax JS Operators JS If Conditions JS Loops JS Strings JS Numbers JS Functions JS Timers JS Objects JS Scope JS Dates JS Temporal  New JS Arrays JS Sets JS Maps JS Iterations JS Math JS RegExp JS Data Types JS Errors JS Debugging JS Style Guide JS Reference JS Projects  New JS Versions JS HTML DOM JS HTML Events JS HTML First

JS Web APIs

JS Window API JS Fetch JS Web API

JS Advanced

JS Functions JS Objects JS Classes JS JSON JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Graphics

Old Technologies

JS AJAX JS jQuery JS JSONP

JS Examples

JS Examples

JavaScript Fetch API

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.

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

// Fetch a file
fetch(file)
  .then(function(response) {
     return response.text();
  })
  .then(function(data) {
    myDisplayer(data);
  });
Try it Yourself »

Or (using arrows)

// Fetch a file
fetch(file)
  .then(response => response.text())
  .then(data => myDisplayer(data));
Try it Yourself »

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

Using an Asynchronous Function

// Async function to fetch a file
async function loadText(file) {
  const response = await fetch(file);
  myDisplayer(await response.text());
}
Try it Yourself »

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.

Property Description
ok True if the request succeeded
status The HTTP status code
statusText The HTTP status message
url The HTTP url address

Example

The result is a Response object [object Response].

// Async function to download a file
async function loadText(file) {
  const response = await fetch(file);
  myDisplayer(response);
}
Try it Yourself »

The ok Property

Example

The response.ok should be true.

// Async function to download a file
async function loadText(file) {
  const response = await fetch(file);
  myDisplayer(response.ok);
}
Try it Yourself »


The status Property

Example

The response.status should be 200.

// Async function to download a file
async function loadText(file) {
  const response = await fetch(file);
  myDisplayer(response.status);
}
Try it Yourself »

The url Property

Example

// Async function to download a file
async function loadText(file) {
  const response = await fetch(file);
  myDisplayer(response.url);
}
Try it Yourself »

Asynchrounous Output

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

Example

// Async function to download a file
async function loadText(file) {
  const response = await fetch(file);
  myDisplayer(response.url);
}

loadText("fetch.txt");
myDisplayer("JavaScript continues.");
Try it Yourself »

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.

Method Description
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

async function loadText(file) {
  const response = await fetch(file);
  if (!response.ok) {
    myDisplayer(response.status + " " + response.statusText);
    return;
  }
  myDisplayer(await response.text());
}
Try it Yourself »

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

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->