Aller au contenu principal
← ⚡ JavaScript & the browser·Module C4 · Leçon 3
Tâchefetch('/api/user') is mocked to return {"name":"Anna","age":30}. Check r.ok and throw on bad status; parse JSON; log the user's name. Use try/catch.

Les bases de fetch() : un GET qui ne ment pas sur les erreurs

100 XP8 min
Théorie

The smallest real fetch

const r = await fetch("/api/user");
const user = await r.json();
console.log(user.name);

Two awaits. Same as a curl. fetch returns a Response; .json() parses the body as JSON and returns a Promise of the parsed value.

The error trap

fetch only rejects on network failure (DNS failed, CORS blocked, offline). A 404, 500, 403 — those are resolved responses. The body just contains an error page.

const r = await fetch("/api/user");
if (!r.ok) {
  // r.status is 4xx or 5xx, fetch DIDN'T throw
  throw new Error(`HTTP ${r.status}`);
}

This is the #1 bug new fetch users write: assuming a 500 will land in your .catch. It won't. You have to check r.ok (true if status is 200-299) or r.status directly.

Other response methods

r.text();      // body as string
r.blob();      // body as Blob (images, downloads)
r.arrayBuffer(); // body as raw bytes

You can only consume the body once. await r.json() then await r.text() on the same response throws.

Headers

r.headers.get("content-type");   // "application/json; charset=utf-8"
r.headers.get("x-ratelimit-remaining");

Headers is a Map-like object. .get is case-insensitive — HTTP headers are.

🔒

Inscris-toi pour coder

La théorie est ouverte à tous. L'éditeur, l'aperçu live et le check se débloquent avec un essai gratuit de 7 jours — carte requise, annulable à tout moment.

S'inscrire — essai gratuit →

Les 10 premières leçons de chaque parcours sont gratuites. Pas de carte requise.

← PrécédentLeçon suivante →

Recevez une astuce Python ou web par jour — par email

Court, écrit à la main, sans spam. Désabonnement en un clic.