JavaScript Fetch API

Introduction

The Fetch API lets you make HTTP requests using JavaScript. It replaces old APIs like XMLHttpRequest and gives you a clean, promise-based interface for loading data from servers.

1. Basic GET Request

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(res => res.json())
  .then(data => console.log(data));
    

2. Using async/await (cleaner)

async function loadPost() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const data = await res.json();
  console.log(data);
}

loadPost();
    

3. POST Request (Sending Data)

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    title: "Hello",
    body: "This is a test.",
    userId: 1
  })
})
  .then(res => res.json())
  .then(data => console.log(data));
    

4. Handling Errors

async function loadData() {
  try {
    const res = await fetch("https://wrong-url.com/data");
    if (!res.ok) throw new Error("Server error");
    const data = await res.json();
  } catch (err) {
    console.error("Fetch failed:", err);
  }
}
    

5. Fetch Options

6. JSON Response Handling

const res = await fetch(url);
const data = await res.json(); // parse JSON
    

7. Example: Display Data on a Page

async function showUser() {
  const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
  const user = await res.json();
  document.getElementById("output").innerText = user.name;
}

showUser();
    

HTML:

8. Fetching Text, Images, and More

const res = await fetch("data.txt");
const text = await res.text();

const imgRes = await fetch("car.png");
const blob = await imgRes.blob();
    

9. Abort Fetch (Cancel Request)

const controller = new AbortController();

fetch(url, { signal: controller.signal });

// cancel after 1 second
setTimeout(() => controller.abort(), 1000);
    

Summary