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
- Make a GET request:
javascript const res = await fetch("/api/items"); if (!res.ok) throw new Error(res.statusText); const items = await res.json(); - 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" }) }); - Abort a request with AbortController:
javascript const controller = new AbortController(); fetch("/api/data", { signal: controller.signal }); controller.abort();
Tips
fetchonly rejects on network failure; HTTP errors (4xx, 5xx) resolve normally, so checkresponse.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-Typeheaders cause servers to reject JSON payloads.