Перейти до основного вмісту
← ⚡ 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.

основи fetch(): GET, який не бреше про помилки

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-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.