Fetch Summary
The Fetch API handles GET, POST, file uploads, query params, streaming, caching, and CORS. Build a wrapper for token injection and error normalisation. Use AbortController to cancel stale requests.
The Fetch API handles GET, POST, file uploads, query params, streaming, caching, and CORS. Build a wrapper for token injection and error normalisation. Use AbortController to cancel stale requests.
async function apiFetch(path, { method = "GET", body, signal } = {}) {
const res = await fetch(`/api${path}`, {
method, signal,
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${getToken()}` },
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
A 20-line fetch wrapper eliminates 80% of HTTP boilerplate across your entire app.
More in JavaScript
This is the last lesson in this section.
Create a free account to earn a certificate