fetch() Basics
Making GET requests, reading JSON responses, and handling the two-step promise
Skills taught: api.fetch-get, api.response-json, api.response-ok, api.fetch-error
Using fetch() to make HTTP requests
// ── Basic GET request ──
async function getUser(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
// fetch() does NOT throw for 4xx/5xx — check .ok
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
const user = await res.json(); // parses JSON body
return user;
}
// ── With error handling ──
try {
const user = await getUser(1);
console.log(user.name, user.email);
} catch (err) {
console.error('Failed to load user:', err.message);
}
// ── Check response metadata ──
async function fetchWithInfo(url) {
const res = await fetch(url);
console.log('Status:', res.status, res.statusText);
console.log('Content-Type:', res.headers.get('content-type'));
console.log('Cache-Control:', res.headers.get('cache-control'));
console.log('Was redirected:', res.redirected);
return res.ok ? await res.json() : null;
}
// ── Timeout via AbortController ──
async function fetchWithTimeout(url, timeoutMs = 5000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, { signal: controller.signal });
return await res.json();
} catch (err) {
if (err.name === 'AbortError') throw new Error('Request timed out');
throw err;
} finally {
clearTimeout(timer);
}
}
Tip: fetch() only rejects (throws) on network failure — not on 404 or 500 responses. Always check `if (!res.ok)` after awaiting, and throw manually if you want HTTP errors to be catchable.
Frequently Asked Questions
Should I use fetch() or axios?
fetch() is built-in and sufficient for most use cases. Use axios when you need: (1) automatic JSON serialization for request bodies (fetch requires JSON.stringify manually), (2) interceptors to add auth headers or handle errors globally, (3) request cancellation tokens (cleaner than AbortController), (4) upload progress events, (5) Node.js support < 18. For a browser-only app with simple needs, fetch() + a small wrapper function is the leaner choice.