Прескочи на главни садржај
← ⚡ JavaScript & the browser·Модул C4 · Лекција 3
Задатакfetch('/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.

фетцх() основе: ГЕТ који не лаже о грешкама

100 XP8 min
Теорија

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.

🔒

Региструј се да почнеш са кодом

Теорија је отворена за све. Едитор, преглед уживо и провера се откључавају са 7-дневним бесплатним пробним периодом — потребна картица.

Регистрација — бесплатан пробни период →

Првих 10 лекција у сваком путу су бесплатне. Без картице.

← ПретходнаСледећа лекција →

Један савет за Python или веб дневно — на имејл

Кратко, ручно писано, без спама. Одјава у једном клику.