Skip to main content
← ⚑ JavaScript & the browserΒ·Module C4 Β· Lesson 3
Taskfetch('/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.

JavaScript fetch() Tutorial: GET requests + the r.ok trap

100 XP8 min
Theory

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.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.