Fetch & XHR
The fetch API is the modern way to make HTTP requests from the browser. It returns Promises, supports async/await, and handles JSON, files, and streaming. XHR is the legacy alternative — still needed for upload progress events.
How do you make an API request with fetch?
Call fetch(url), which returns a promise of a Response. Check response.ok, then read the body with await response.json() (or .text()). For POST requests, pass an options object with method, headers and a body, usually JSON.stringify(data). Cancel requests with an AbortController.
const res = await fetch("https://api.example.com/posts?limit=5");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const posts = await res.json();
await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello" }),
});
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal }); ctrl.abort();Fetch vs XHR
Response Body Methods
res.json()Parse body as JSON → Promise<any>res.text()Read as UTF-8 string → Promise<string>res.blob()Read as Blob (images, audio…)res.arrayBuffer()Read as raw binary ArrayBufferres.formData()Read as FormData (service worker use)res.bodyReadableStream for streaming reads⚠️ A response body can only be consumed ONCE. Clone with res.clone() if you need to read it twice.
HTTP Methods Cheatsheet
GETfetch('/api/users')
.then(r => r.json())POSTfetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' }),
})PUT / PATCHfetch('/api/users/42', {
method: 'PUT', // or 'PATCH'
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Bob' }),
})DELETEfetch('/api/users/42', { method: 'DELETE' })
.then(r => r.ok || Promise.reject(r.status))Common Pitfalls
Interactive Fetch Demo
Code Editor
<button id="load">Load posts</button>
<ul id="posts"></ul>
<p id="err"></p>Preview
Fetch API — step by step
fetch() returns a two-step Promise
fetch(url) resolves to a Response object as soon as the HTTP headers arrive — NOT after the body is downloaded. You then call response.json(), response.text(), or response.blob() to get another Promise that resolves when the body is fully received. This two-step model means you always need two awaits (or two .then() calls).
🎯 Quick Check
A fetch() call returns a Response with status 404. What happens?
Fetch API: summary
Key points
fetchrejects only on network errors; HTTP 404 and 500 still resolve, so checkres.ok.- Requests to another domain must be allowed by that server's CORS headers.
- Add
credentials: "include"to send cookies cross-origin. XMLHttpRequestis the older API; usefetchin new code.
Frequently asked questions
›Why am I getting a CORS error with fetch?
The server you're calling doesn't allow your origin. It has to send Access-Control-Allow-Origin; you can't fix this from the browser. Call it from your own backend instead.
›How do I set a timeout on fetch?
Pass signal: AbortSignal.timeout(5000) in the options.