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

JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web API JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


JavaScript Fetch API

The Fetch API lets JavaScript download resources from a web server.

It can be used to load text files, JSON data, images, and many other types of resources.

The download is asynchronous.

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

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

Fetching a Text File

The simplest use of fetch() is to download a text file.

Example

Code:

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

// Call the async function
loadText("demo.txt");

Text file:

<p>The Fetch API interface allows web browser to make HTTP requests to web servers.</p> <p>If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.</p>
Try it Yourself »

The Response Object

fetch() retuns a Promise that resolves to a Response object.

Example

The result is a Response object.

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

The Response object contains information about the server response.

Property / Method Description
ok True if the request succeeded.
status The HTTP status code.
statusText The HTTP status message.
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

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 »

Fetching JSON

The json() method converts a JSON response into a JavaScript object.

Example

async function loadCustomer() {
  const response = await fetch("customer.json");
  const customer = await response.json();
  myDisplayer(customer.name);
}

// Call the async function
loadCustomer();
Try it Yourself »

Loading Multiple Files

Independent downloads can run in parallel.

Example

// Async function to download files
async function loadData() {
  const [customerResponse, productsResponse, newsResponse] = await Promise.all([
    fetch("customer.json"),
    fetch("products.json"),
    fetch("news.json")
  ]);
  const customer = await customerResponse.json();
  const products = await productsResponse.json();
  const news = await newsResponse.json();
  myDisplayer("Custome name: " + customer.name);
  myDisplayer(products.length + " products");
  myDisplayer(news.length + " news items");
}

// Call the async function
loadData();
Try it Yourself »

Checking for Errors

fetch() resolves when the server responds.

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

Instead, check the ok property.

Example

// Async function to download a file
async function loadText() {
  const response = await fetch("fetch.txt");
  if (!response.ok) {
    throw new Error(response.status + " " + response.statusText);
  }
  return await response.text();
}
Try it Yourself »

Handling Errors

Use try...catch to handle errors.

Example

// Async function to download a file
async function loadText() {
  try {
    const response = await fetch("fetch.txt");
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    myDisplayer(await response.text();
  } catch(err) {
    myDisplayer(err.message);
  }
}
Try it Yourself »

Important: HTTP Errors

A common beginner mistake is expecting fetch to fail on Http errors like 404 or 500.

Fetch only rejects on network errors.

A 404 response is not a rejected promise.

You must check response.ok.

The above example handles HTTP errors correctly.


Summary

  • The fetch() method downloads resources from a server.
  • fetch() returns a Promise that resolves to a Response object.
  • Use text() to read text responses.
  • Use json() to read JSON responses.
  • Use Promise.all() to download multiple resources in parallel.
  • Check response.ok to detect HTTP errors.
  • Use try...catch to handle errors.

Common fetch Mistakes

Forgetting await gives you a promise instead of data.

Example

async function loadData() {
  let response = await fetch("data.json");
  let data = response.json();
  myDisplayer(data);
}

This logs a promise.

You must use await to get the JSON.

Example

async function loadData() {
  let response = await fetch("data.json");
  let data = await response.json();
  myDisplayer(data);
}

Debugging Tip

Most fetch bugs are not JavaScript bugs.

They are path and response problems.

If fetch is not working, check the console.

Then check the Network tab.

  • Is the file path correct.
  • Is the status code 200.
  • Is the response JSON.

Next Chapter

The next page shows how to debug async code like a professional.

You will learn breakpoints, logging patterns, and why async errors feel invisible.

Debugging Asynchronous JavaScript


×

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.

-->