SyntaxStudy
Sign Up
HTML Intermediate 4 min read

Fetch API

Fetch API

The Fetch API is the modern way to make HTTP requests from the browser. It returns Promises and replaces older XMLHttpRequest.

Example
// GET request
fetch("/api/users")
  .then(res => res.json())
  .then(users => console.log(users))
  .catch(err => console.error(err));

// POST request with JSON body
fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Alice", email: "a@x.com" })
})
.then(res => res.json())
.then(data => console.log("Created:", data));
Pro Tip

fetch() only rejects on network errors — HTTP 4xx/5xx still resolve, so check res.ok.