Web Development Pro | Lesson 033 | Fetch and HTTP Responses
Web Development Pro · Lesson 33 of 60
Module 4: Data, modules, and state
In this lesson
Prerequisites and learning outcomes
Complete lesson 32 first. This lesson builds on requests, status checks, and json bodies. By the end, you can load local JSON over HTTP and distinguish transport failure from HTTP errors. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Load a local data resource over HTTP
Keeping workshop records in a JSON file separates content from interface code. Fetch requests a resource and returns a promise for a Response. The response contains status information and a body that can be read asynchronously. Loading data therefore has at least two relevant stages: obtaining a response and consuming its body.
Use the supplied workshops.json alongside the module files. Serve the folder with an already available local HTTP server as described in lesson 31. Direct file opening is not a reliable fetch workflow. This exercise needs no external API, credentials, account, or deployment; all data remains fictional and local to the practice server.
Check status before reading the result
Fetch does not reject merely because the server returns a 404 or 500 response. Those are HTTP responses, so the promise can fulfill with a Response whose ok property is false. Network failures and some browser-enforced access failures can reject instead. Treat these as distinct paths even when the visitor-facing message is similarly concise.
File api.mjs:
export async function loadWorkshops(url, fetchImpl = fetch) {
const response = await fetchImpl(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
}
The optional fetchImpl parameter defaults to the browser's fetch function. Tests can supply a controlled replacement without contacting a network. This is dependency injection in a small practical form: the function's source of responses is explicit. The default still makes ordinary browser use straightforward.
Response.ok corresponds to successful HTTP status codes in the 200–299 range. A 204 response has no content, so attempting to parse it as JSON can still fail. Success at the HTTP layer is not a guarantee that the body exists, is valid JSON, or matches the application's record contract.
Keep parsing separate from validation
Response.json reads the body and parses JSON into JavaScript values. It can reject on malformed JSON. Valid JSON can also describe the wrong shape, such as an object where your code expects an array. Lesson 35 will validate the application contract explicitly; here the supplied file is a known array of title records.
A response body is generally consumed once. Calling response.json and then response.text on the same body is not a normal way to inspect it twice. If you genuinely need separate consumers, understand cloning and its costs. For a small loader, read once and pass the parsed value onward.
JSON is a data format, not executable JavaScript source. It uses double-quoted property names and strings, and does not support comments or trailing commas. Do not use eval to parse a downloaded file. JSON.parse or response.json provides the appropriate data parsing behavior without executing arbitrary code.
Present an honest loading state
File app.mjs:
import { loadWorkshops } from './api.mjs';
const output = document.querySelector('#fetch-output');
if (!output) throw new Error('Fetch output is missing.');
export async function showWorkshops() {
output.textContent = 'Loading workshop data…';
try {
const items = await loadWorkshops('./workshops.json');
output.textContent = items.map(item => item.title).join(' • ');
} catch (error) {
output.textContent = 'Workshop data could not load. Check the local server and file.';
console.error(error.message);
}
}
export const ready = showWorkshops();
This small display uses textContent, so returned titles are not parsed as HTML. It does not yet provide the full list renderer or validate every record. Keeping the lesson focused makes the HTTP contract visible before the final directory combines loading, validation, state, and rendering.
The relative fetch URL in this browser call resolves against the document's base URL. Relative module import paths instead resolve against the importing module. Those bases often coincide in a small folder, but they can differ after files move into subdirectories. Use new URL relative to import.meta.url when you deliberately want a module-relative resource, and explain that choice rather than relying on coincidence.
Diagnose failures with evidence
If loading fails, inspect the requested URL, status, response headers, and response body in the Network panel when a browser is available. A server may return an HTML error page where JSON was expected. The resulting parse error is a symptom; the wrong URL or server response may be the real cause.
Cross-origin requests are governed by browser security rules. Adding mode: 'no-cors' does not grant readable access to an otherwise disallowed response; it commonly gives an opaque response unsuitable for this JSON workflow. Prefer the same-origin local file here. Later security lessons explain origins and CORS more fully.
Do not put API secrets into app.mjs to “fix” a rejected request. Everything delivered to a browser can be inspected by its user. A service requiring private credentials needs an appropriate server-side boundary, not a hidden-looking client variable.
Test the response contract locally
The automated loader tests supply a successful response, a 404 response, a rejected network promise, and a body parser that throws. They also confirm the requested URL and ensure JSON parsing is not attempted after a rejected HTTP status. A known local JSON file is parsed separately and compared with the expected titles.
These tests exercise the exact loader with controlled response objects. They do not send real HTTP traffic or verify browser CORS, MIME behavior, or server configuration. Complete those browser checks on your own machine before claiming the delivery path works end to end.
Worked practice
Worked exercise 1: Handle a fulfilled 404
Task: Fetch resolves, but response.status is 404. Worked answer: test response.ok and throw or return an explicit failure before treating the body as successful workshop data. A fulfilled fetch promise alone does not mean the resource was found.
Worked exercise 2: Diagnose an HTML body
Task: response.json throws and the response body starts with a website error page. Worked answer: check the URL and server response first. The JSON parser is correctly rejecting HTML; changing the parser will not repair a missing data file.
Worked exercise 3: Preserve a testable loader
Task: A test should simulate network failure without disabling the actual network. Worked answer: pass a fetchImpl function that returns a rejected promise. This tests the failure contract deterministically while leaving the production default fetch behavior unchanged.
Knowledge check
Question 1
Does fetch normally reject solely because the server returns 404? A) Yes, before creating a Response. B) No; inspect the Response status or ok value. C) Yes, once the response headers are available. D) Yes, provided the URL is relative to the page.
Check question 1: answer and explanation
Answer: B. HTTP error statuses can still fulfill the fetch promise.
Question 2
What does response.json establish? A) JSON parsing, not the full application schema. B) That the parsed collection follows the required record contract. C) Unique record ids. D) Guaranteed array shape.
Check question 2: answer and explanation
Answer: A. Parsed data still needs contract validation.
Question 3
Why can a 204 response fail this loader? A) It indicates an unsuccessful status even when ok is true. B) Its status is outside 200–299. C) It has no JSON body to parse. D) It automatically substitutes an empty array for the missing body.
Check question 3: answer and explanation
Answer: C. HTTP success and a usable JSON payload are separate conditions.
Question 4
What does no-cors fail to provide for this use case? A) A promise that can settle when the request receives an opaque response. B) The ability to specify a request URL. C) A request under the mode’s restricted rules. D) Readable access to otherwise restricted JSON data.
Check question 4: answer and explanation
Answer: D. An opaque response is not a bypass for reading protected cross-origin content.
Question 5
Why inject fetchImpl in tests? A) To control responses and failures without real network traffic. B) To prove the live server sends the same headers as the fixture. C) To replace the need for malformed-body tests. D) To verify browser CORS without a browser.
Check question 5: answer and explanation
Answer: A. Explicit dependencies make contract tests reproducible.