HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Web Fetch API

The Web Fetch API is a modern, powerful, and more flexible interface for making network requests (fetching resources across the network). It is the successor to the old XMLHttpRequest and is built on Promises, making it much easier to handle asynchronous data.


Remote Data Fetcher

Use the buttons below to trigger real network requests. One fetches a local text file, and the other fetches live JSON data from an external API:

Click a button to start a request...

Why Use Fetch API?

  • Modern Syntax: Clean, readable code using Promises.
  • Native Support: Built into all modern browsers.
  • Versatile: Can handle text, JSON, blobs, and more.
  • No Callbacks: Avoids "callback hell" by using `.then()` chains or `async/await`.

The basic fetch() Syntax

The fetch() method takes one mandatory argument: the path to the resource you want to fetch. It returns a Promise that resolves into a Response object.

fetch("example.txt")
    .then(response => response.text())
    .then(data => {
        console.log(data); // "Hello World"
    })
    .catch(error => {
        console.error("Error: ", error);
    });

Fetching JSON Data

When working with modern web applications, you will mostly fetch JSON data. The Fetch API provides a .json() method to automatically parse the response.

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(x => x.json())
    .then(y => {
        console.log(y.title); // Title of the post
    });
Tip: Always include .catch() to handle network failures like lost internet connection or server downtime.

Fetch vs XMLHttpRequest

Feature Fetch API XMLHttpRequest (XHR)
Syntax Promise-based (Modern) Callback-based (Old)
Simplicity Very Simple Complex/Verbose
Status Handling Does not reject on 404/500 Handles status manually
Important: A fetch() promise will not reject on HTTP error status (like 404 or 500). It only rejects on network failure. You should check response.ok to ensure the request was successful.

Key Points to Remember

  • fetch() is the standard for modern web requests.
  • It returns a Promise that resolves to a Response.
  • Use .text() for raw text and .json() for objects.
  • The Promise only rejects on **network errors**, not HTTP errors.
  • It is often used with async/await for even cleaner code.
  • It allows for complex settings like headers, POST methods, and CORS.