Skip to chapter content
navan✳THE BUILD LABJAVASCRIPT
0/31 read
CHAPTER 28 / 31THE BROWSER

A request is a conversation.

fetch resolves for HTTP errors; status and body need separate checks.

01 / THE BASICS

Start here.

A browser can ask a server for information using HTTP. A request has a URL, a method such as GET or POST, and sometimes headers or a body. The server sends back a response with a status, headers, and a body. A successful GET might return JSON, a text format for objects and arrays. JavaScript's fetch function starts a request and returns a promise for a Response object.

The first await gives you the response, not yet a parsed JavaScript object. Calling response.json() reads and parses the body asynchronously, so it also returns a promise. You usually check response.ok before treating the body as a successful result. fetch normally fulfills its promise even for an HTTP error status such as 404; a network failure is different and can reject the promise. Those are two failure paths to understand separately.

Imagine asking for /api/books. The URL chooses the resource; GET asks to read it. If the server returns status 200 with JSON, await response.json() gives you data to inspect. If the status is 404, the server answered but did not find that resource. If the network is unavailable, there may be no response at all. A clear program explains each outcome to the user rather than assuming every response contains usable data.

02 / THE IDEA

Build the model.

HTTP exchanges a request for a response with a status, headers, and often a body. fetch returns a promise for the response. A server's 404 or 500 response still counts as a completed exchange, so fetch normally fulfills; network failures reject.

Check response.ok before treating a body as success. Reading JSON is another asynchronous step that can fail if the body is empty or malformed. A request may also need an AbortController to stop waiting after a timeout or when a user leaves the screen.

03 / UNDER THE SURFACE

How it works.

fetch starts an HTTP request and returns a promise for a Response. A fulfilled fetch means a response arrived, not that the server approved the request. Response.ok is true for successful 2xx status codes; inspect status or ok before treating the body as success. A network failure, such as an unreachable server, normally rejects the promise instead.

The response body is a stream that must be read. response.json() returns another promise because reading and parsing take time; it can reject if the body is empty or invalid JSON. A robust request therefore has three checks: did transport produce a response, did HTTP report success, and is the returned data shaped as expected? AbortController can cancel an outstanding request when the user navigates away or the operation times out.

04 / A WORKED EXAMPLE

Read it line by line.

JAVASCRIPT / Worked example
const response = await fetch('/api/items');
if (!response.ok) throw new Error('Request failed');
const items = await response.json();

First notice. The status check and JSON parse answer different questions.

await fetch waits for the response headers. If the server replied with 404, response exists and the await does not throw for that status. The explicit !response.ok check throws your own error. Only a successful response reaches response.json(), which reads and parses the body before assigning items.

05 / ANOTHER EXAMPLE

See the rule again.

JAVASCRIPT / Another example
try {
  const response = await fetch('/api/items');
  if (!response.ok) throw new Error('HTTP ' + response.status);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error('Could not load items', error);
}

A non-2xx response triggers the explicit throw. A network failure or bad JSON rejects one of the awaited promises. All three paths reach catch. For a user interface, replace the console error with a helpful visible message and consider validating the parsed data's shape.

06 / KEEP THIS

One thing to remember.

Transport success, HTTP success, and valid data are separate layers.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗JavaScript · Understand the language behind the interface.