What is the Fetch API?
The Fetch API is the modern, promise-based way to make HTTP requests in the browser, replacing the old XMLHttpRequest.
Returns a Promise — that resolves to a Response object.
Two steps — first await the response, then parse the body (e.g. with .json()).
Options — set method, headers, and body for POST and other requests.
Gotcha: fetch only rejects on network failure — HTTP errors like 404 or 500 still resolve, so check response.ok yourself.
// GET request
const response = await fetch('/api/users');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const users = await response.json();
// POST request
const newUser = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John', email: 'john@test.com' })
});
const created = await newUser.json();
// With error handling
async function fetchData(url) {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP Error: ${res.status} ${res.statusText}`);
}
return await res.json();
} catch (err) {
if (err.name === 'AbortError') {
console.log('Request cancelled');
} else {
console.error('Fetch failed:', err.message);
}
throw err;
}
}
// With AbortController (cancellation)
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(r => r.json())
.catch(err => {
if (err.name === 'AbortError') console.log('Cancelled');
});
controller.abort(); // Cancel the requestfetch returns a Promise. response.ok checks for HTTP success (200-299). response.json() parses the body. POST requires method, headers, and JSON.stringify body.
AbortController enables request cancellation. fetch does NOT reject on 404/500 — always check response.ok.
The #1 gotcha: fetch does NOT reject on HTTP errors (404, 500). Always check response.ok.
Show GET, POST, error handling, and AbortController. Know that response.json() returns a Promise (must await twice: await fetch, then await .json).