Fetch API
Make HTTP requests from the browser with fetch — GET, POST, headers, errors
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
The is the modern way to make HTTP requests from the browser.
Basic GET:
javascript const res = await fetch('https://api.example.com/users'); const data = await res.json();
Always check res.ok — fetch only rejects on network errors, NOT on 4xx/5xx: ``javascript const res = await fetch('/api/data'); if (!res.ok) throw new Error(HTTP ${res.status}); const data = await res.json();
POST with JSON:
javascript const res = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Alice', age: 30 }), });
Common response methods:
res.json()— parse body as JSON (returns Promise)res.text()— body as stringres.blob()— binary datares.ok— true if status 200-299res.status— HTTP status code
Authorization header:
javascript fetch('/api/protected', { headers: { 'Authorization': Bearer ${token} } });
Examples
Full CRUD fetch wrapper
A minimal fetch wrapper handles headers and error checking in one place
async function api(url, options = {}) {
const res = await fetch(url, {
headers: { 'Content-Type': 'application/json', ...options.headers },
...options,
body: options.body ? JSON.stringify(options.body) : undefined,
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
// Usage
const users = await api('/api/users');
const newUser = await api('/api/users', { method: 'POST', body: { name: 'Bob' } });Abort controller — cancel a request
AbortController lets you cancel in-flight requests
const controller = new AbortController();
fetch('/api/slow-endpoint', { signal: controller.signal })
.then(r => r.json())
.then(console.log)
.catch(e => { if (e.name !== 'AbortError') throw e; });
// Cancel if user navigates away
setTimeout(() => controller.abort(), 5000);How well did you understand this?
Next in JavaScript Core
Classes