Preskoči na glavni sadržaj
← ⚡ JavaScript & the browser·Modul C4 · Lekcija 3
Zadatakfetch('/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.

fetch() osnove: GET koji ne laže o pogreškama

100 XP8 min
Teorija

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.

🔒

Registriraj se i počni kodirati

Teorija je otvorena svima. Editor, pregled uživo i provjera otključavaju se s 7-dnevnim besplatnim probnim periodom — potrebna kartica, otkaži kad god.

Registracija — besplatan probni period →

Prvih 10 lekcija u svakom smjeru je besplatno. Bez kartice.

← PrethodnaSljedeća lekcija →

Jedan Python ili web savjet dnevno — emailom

Kratko, ručno pisano, bez spama. Odjavi se jednim klikom.