~/hackweb.dev
Fetch API
Quiz
...

Fetch API

advanced · updated Tue Sep 08 2026Contribute

Make HTTP requests to fetch data from servers.

Fetch API

The Fetch API provides a modern way to make HTTP requests, replacing XMLHttpRequest.

Basic GET

fetch("https://api.example.com/users")
  .then(response => {
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log("Failed:", error.message));

Remember: fetch() only rejects on network errors, not HTTP errors like 404 or 500. Always check response.ok.

Response Object

fetch("/api/data").then(response => {
  console.log(response.status);  // 200, 404, 500
  console.log(response.ok);      // true for 200-299
  return response.json();
});

Key methods: .json(), .text(), .blob(). All return Promises.

POST with Headers and Body

fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": "Bearer token123"
  },
  body: JSON.stringify({ name: "John", email: "[email protected]" })
})
.then(r => r.json())
.then(data => console.log("Created:", data));

Canceling with AbortController

const controller = new AbortController();

fetch("/api/data", { signal: controller.signal })
  .then(r => r.json())
  .catch(error => {
    if (error.name === "AbortError") console.log("Canceled");
  });

setTimeout(() => controller.abort(), 2000);

Tip: Cancel requests when users navigate away or when a newer request supersedes an older one.

Weather App Example

async function getWeather(city) {
  try {
    let response = await fetch(`https://api.weather.com/city/${city}`);
    if (!response.ok) throw new Error(`City "${city}" not found`);
    let weather = await response.json();
    console.log(`Temperature: ${weather.temp}°C`);
    return weather;
  } catch (error) {
    console.log("Weather fetch failed:", error.message);
  }
}

POST Form Data

async function submitForm(formData) {
  let response = await fetch("https://api.example.com/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(formData)
  });
  if (!response.ok) throw new Error("Form submission failed");
  return await response.json();
}

Best Practices

  • Always check response.ok — Fetch doesn’t reject on HTTP errors
  • Use try/catch — Handle both network and HTTP errors
  • Set Content-Type — Server needs to know how to parse the body
  • Use AbortController — Cancel unnecessary requests

Common Mistakes

  • Not checking response.ok — Treating 404/500 as success
  • Forgetting to parsefetch() returns Response, not data
  • Missing Content-Type — Server may ignore the body
  • Not handling network errorsfetch() throws on failures