How to use the fetch API in JavaScript

· Category: JavaScript

Short answer

fetch returns a Promise that resolves to a Response object. You must check response.ok and call methods like .json() or .text() to read the body.

Steps

  1. Make a GET request: javascript const res = await fetch("/api/items"); if (!res.ok) throw new Error(res.statusText); const items = await res.json();
  2. Make a POST request with JSON: javascript const res = await fetch("/api/items", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "New item" }) });
  3. Abort a request with AbortController: javascript const controller = new AbortController(); fetch("/api/data", { signal: controller.signal }); controller.abort();

Tips

  • fetch only rejects on network failure; HTTP errors (4xx, 5xx) resolve normally, so check response.ok.
  • Use credentials: "include" to send cookies in cross-origin requests.

Common issues

  • Calling .json() multiple times throws because the body stream is already consumed.
  • Missing Content-Type headers cause servers to reject JSON payloads.