Episode 1 — Fundamentals / 1.16 — Using Browser Functionalities in JavaScript
1.16.d — Fetch API
In one sentence:
fetchis the modern Promise-based way to make HTTP requests from the browser — it returns aResponseyou must inspect (ok,status) and parse (.json(),.text(), …) because network errors and HTTP 4xx/5xx behave differently.
Navigation: ← 1.16.c — Storage & Cookies · 1.16 Overview
1. Basic GET
const res = await fetch("https://api.example.com/users/1");
fetch returns a Promise that resolves to a Response — even when the server returns 404 or 500. That is not a rejected promise by default.
2. Check ok and status
const res = await fetch("/api/profile");
if (!res.ok) {
console.error("HTTP", res.status, res.statusText);
throw new Error(`Request failed: ${res.status}`);
}
const data = await res.json();
| Property | Meaning |
|---|---|
res.ok | true for status 200–299 |
res.status | Numeric code (200, 404, 500, …) |
res.statusText | Short text ("OK", "Not Found", …) |
3. Parsing the body
Body can only be read once — choose one:
await res.json(); // JSON
await res.text(); // plain text / HTML
await res.blob(); // binary (images, files)
If you call .json() twice on the same Response, the second call fails.
4. POST with JSON
const res = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
headers is a plain object in simple cases; use Headers for dynamic cases.
5. When fetch rejects
The promise rejects mainly on network failure (offline, DNS, CORS blocked with opaque errors in some cases). HTTP error responses usually resolve — you must check res.ok.
try {
const res = await fetch("/maybe-down");
if (!res.ok) throw new Error(String(res.status));
} catch (e) {
console.error("Network or throw:", e);
}
6. CORS (high level)
Browsers restrict cross-origin requests unless the server sends appropriate CORS headers (see 1.4). fetch to another origin without permission fails in the browser — the same URL might work in curl.
Simple requests vs preflight (OPTIONS) — advanced topic; for now: same-origin fetch “just works”; cross-origin needs server cooperation.
7. Key takeaways
await fetch(url)→Response— always checkok/status.- Parse with
.json()/.text()— single-use body. - Rejections ≈ network; 4xx/5xx are usually resolved responses.
Explain-It Challenge
Explain without notes:
- Why does
fetchreturning 404 not automaticallythrowor reject? - What happens if you call
res.json()twice? - In one sentence: what problem does CORS solve?
Navigation: ← 1.16.c — Storage & Cookies · 1.16 Overview