J

JavaScript Handbook

Clean • Professional

Web Fetch API in JavaScript

2 minute

Web Fetch API

The Fetch API is a modern, built-in web API in JavaScript that allows you to make HTTP requests to servers easily. It is promise-based, meaning it works asynchronously without freezing your web page, making it perfect for loading data dynamically from APIs, sending data to a server, or handling files like images and documents.

GET Request

A GET request is used to retrieve data from a server. With the Fetch API, it’s simple:

fetch("<https://api.example.com/users>")
  .then(response => {
    if(!response.ok) throw new Error("Network response was not ok");
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error("Fetch error:", error));
  • fetch(url) makes a request to the server.
  • response.ok checks if the request succeeded.
  • response.json() converts the response into a usable JSON object.
  • .catch() handles errors gracefully.

POST Request

A POST request sends data to the server, like creating a new user:

fetch("<https://api.example.com/users>", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ name: "John", age: 25 })
})
  .then(response => response.json())
  .then(data => console.log("User created:", data))
  .catch(error => console.error("Error:", error));
  • method: "POST" tells the server you are sending data.
  • headers define the data type (usually JSON).
  • body contains the data, converted to a string with JSON.stringify.
  • The server responds, and you can handle it in .then().

Handling Different Response Types

The Fetch API can handle multiple types of server responses:

  • JSON: response.json() → Parses JSON data.
  • Text: response.text() → Retrieves plain text.
  • Blob: response.blob() → Handles files or images.
  • FormData: response.formData() → Works with HTML form submissions.

Example for Blob:

fetch("example.png")
  .then(res => res.blob())
  .then(blob => console.log(blob));

Abort a Fetch Request

Sometimes, you may want to cancel a request, for example, if a user navigates away before the data loads. You can use AbortController:

const controller = new AbortController();
const signal = controller.signal;

fetch("<https://api.example.com/data>", { signal })
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => {
    if(err.name === "AbortError") console.log("Fetch aborted");
    else console.error(err);
  });

// Abort after 2 seconds
setTimeout(() => controller.abort(), 2000);
  • AbortController creates a signal to control the fetch.
  • Passing { signal } allows you to cancel the request.
  • .abort() stops the request if needed, improving performance.

Benefits of Fetch API:

  • Simple and modern replacement for XMLHttpRequest.
  • Works asynchronously without blocking the UI.
  • Handles JSON, files, and text seamlessly.
  • Supports request cancellation with AbortController.

Article 0 of 0