LESSON 59 · INTERMEDIATE4 min read

Fetch, HTTP & JSON

Speak HTTP from the browser, read JSON safely, and design loading, empty, and error states that tell the truth.

ES2024 / Node.js 20+Free to readModule 13 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Describe how methods, status codes, headers, and JSON bodies fit together.
  • Use fetch with response.ok and defensive parsing instead of assuming success.
  • Render loading, empty, and error states without trusting response data.

01HTTP is a request and a response

Every network call is an HTTP exchange: the client sends a method, a URL, headers, and sometimes a body; the server replies with a status code, headers, and sometimes a body. GET reads, POST creates, PUT replaces, PATCH updates part of a resource, and DELETE removes it. The method states the intent, while the path names the resource.

Status codes are grouped by meaning: 2xx success, 3xx redirection, 4xx client error, and 5xx server error. 200 is an ordinary success, 201 reports a creation, 204 reports success with no body, 400 means the request was malformed, 401 means unauthenticated, 403 means forbidden, 404 means not found, and 429 means too many requests. Read the status before parsing the body.

http-basics.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02fetch resolves even when the server says no

fetch fulfills its promise when a response arrives, including 404 and 500 responses. It rejects for network failures such as a dropped connection, a blocked request, or an abort. That is why checking response.ok is mandatory; skipping it turns an error page into data your code tries to parse.

Read the content-type header before calling response.json(). A proxy or error page may return HTML with a 200 status, and json() will reject with a syntax error that hides the real problem. A small helper that checks the status, verifies the media type, and parses once keeps every caller consistent.

request-json.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Sending JSON with POST

To send JSON, set Content-Type: application/json, serialize the object with JSON.stringify, and choose the method explicitly. The response may be a 201 with the created record and a Location header. If validation fails, the server should return a 4xx status and a machine-readable error body rather than an HTML page.

Do not assume the error body has the shape you expect. Parse it defensively, fall back to the status text, and surface a message that helps the user act. Never render server-provided strings with innerHTML; use textContent so a malicious record cannot inject markup.

create-book.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Loading, empty, error, and CORS

An interface needs four visible states: loading, success with data, success with no data, and error. Show a status message in a live region, mark the results container as busy while loading, disable duplicate submit buttons, and offer a retry action. An empty state is not an error; it means the request succeeded but matched nothing.

CORS is a browser rule, not a server security boundary. The browser sends an Origin header and blocks JavaScript from reading a cross-origin response unless the server allows that origin. Simple requests may skip a preflight, while JSON POSTs often trigger an OPTIONS request first. The server must still authenticate and validate every request.

Treat every response as untrusted input. Check that the value is an array or object, that identifiers have the expected type, and that strings are strings before rendering. Validation at the boundary prevents one malformed record from breaking the whole view, and it keeps unsafe HTML out of the page even when the server is compromised.

render-state.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • HTTP status codes communicate the outcome before you parse the body.
  • fetch fulfills for 4xx and 5xx responses, so check response.ok and the content type.
  • Design loading, empty, and error states explicitly, and render untrusted text with textContent.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Write a safe JSON helper

Create a getJson function that fetches a URL, rejects non-2xx responses with the status in the message, rejects responses whose content type is not JSON, and returns the parsed body.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
async function getJson(url) {  const response = await fetch(url, {    headers: { Accept: "application/json" },  });  if (!response.ok) {    throw new Error(`Request failed with status ${response.status}`);  }  const type = response.headers.get("content-type") ?? "";  if (!type.includes("application/json")) {    throw new Error("Expected a JSON response");  }  return response.json();}getJson("/api/books").then(console.log).catch(console.error);

The helper converts an HTTP failure into a rejected promise and checks the media type before parsing. Callers can use one catch for transport, status, and parsing problems instead of repeating the checks.

02

Exercise 2: Render an empty state safely

Write renderBooks(list, books) that clears a <ul>, shows a single empty-state item when there are no valid books, and otherwise appends one <li> per book using textContent.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function renderBooks(list, books) {  list.replaceChildren();  const valid = books.filter(    (book) => book && typeof book.title === "string" && typeof book.author === "string"  );  if (valid.length === 0) {    const empty = document.createElement("li");    empty.textContent = "No books match your filter.";    list.append(empty);    return;  }  for (const book of valid) {    const item = document.createElement("li");    item.textContent = `${book.title} — ${book.author}`;    list.append(item);  }}

replaceChildren removes stale rows in one operation. Filtering rejects records that do not have the expected string fields, and textContent keeps titles and author names inert instead of interpreting them as HTML.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01A server returns 404 for a fetch request. What happens to the promise?
02Which request header tells the server that the body is JSON?
03What does CORS actually control?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Write a safe JSON helper

Create a getJson function that fetches a URL, rejects non-2xx responses with the status in the message, rejects responses whose content type is not JSON, and returns the parsed body.

EXPECTED OUTPUT
[Process exited with code 0 - No output]
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.