Lesson 15 of 28
In progress
fetch: talking to a server
Send GET and POST requests, check the status before parsing, and show loading and error states that make sense.
fetch is the browser’s built-in way to make HTTP requests. It returns a promise, so you will also meet await, response.json() and the difference between a network failure and an HTTP error.
What you will learn
- Send a GET request and read the JSON response.
- Check
response.okbefore parsing. - Send data with POST and show loading and error states.
A GET request
Editable. Runs in your browser.
loadTodo();
Press Run to see the output.
Two awaits: the first waits for the response headers, the second waits for the body. response.json() parses the body as JSON and returns a promise. Calling response.json() twice fails, because the body can only be read once.
In this runner the request goes to a public test API. If the network is unavailable, the call rejects and the error is visible in the console, which is itself a useful demonstration.
Check the status
fetch rejects only when the request cannot be made: no network, a blocked domain, a CORS failure. It resolves for 404 and 500, because those are valid HTTP responses.
Editable. Runs in your browser.
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
load("https://jsonplaceholder.typicode.com/todos/999999")
.then((data) => console.log(data))
.catch((error) => console.log(error.message));
Press Run to see the output.
response.ok is true for statuses 200 to 299. Throwing turns an HTTP failure into a rejected promise, so a single catch handles both kinds of failure. Without the check, parsing an error page as JSON throws a confusing SyntaxError instead.
response.status and response.statusText are useful for messages and logs. Do not show the raw text to users; map common codes to a sentence.
POST with JSON
Editable. Runs in your browser.
if (!response.ok) {
throw new Error(`Could not save: ${response.status}`);
}
return response.json();
}
createTask("Ship the lesson").then((saved) => console.log(saved));
Press Run to see the output.
The body must be a string, so objects go through JSON.stringify. The Content-Type header tells the server how to parse it. For form uploads, pass a FormData object as the body and let the browser set the header, including the multipart boundary.
credentials: "include" sends cookies cross-origin, which most APIs require explicitly. Do not enable it casually; it broadens what a page can do with a signed-in session.
Headers and CORS
Request headers describe what you send and what you accept. Accept: application/json states the expected response; Content-Type states what the body contains. A server may also require an API key or an authorization header, which belongs in server-side code whenever possible, because anything in the browser is visible.
CORS is the browser’s rule for cross-origin reads. The server must send Access-Control-Allow-Origin for the requesting origin. When it does not, the request may still reach the server, but the browser hides the response and the promise rejects with a network error. A CORS failure is a server configuration issue; no client header can fix it.
Loading, success and failure
A request is a state machine, and the interface should show which state it is in.
Editable. Runs in your browser.
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
element.textContent = data.title ?? "No title";
} catch (error) {
element.textContent = "Could not load. Try again.";
console.warn(error.message);
}
}
const out = document.createElement("p");
document.body.append(out);
show("https://jsonplaceholder.typicode.com/todos/2", out);
Press Run to see the output.
The user sees a loading state, then either content or a plain-language error. The technical detail goes to the console. That split is the whole pattern, and it is worth applying consistently.
Cancelling and timeouts
A request that never resolves should not leave a spinner forever. AbortController cancels a fetch and rejects its promise with an AbortError.
Editable. Runs in your browser.
try {
const response = await fetch(url, { signal: controller.signal });
return response.ok;
} finally {
clearTimeout(timer);
}
}
withTimeout("https://jsonplaceholder.typicode.com/todos/1", 3000)
.then((ok) => console.log("ok:", ok))
.catch((error) => console.log(error.name));
Press Run to see the output.
Clearing the timer in finally prevents a stray abort after a fast response. Check for error.name === "AbortError" when you need to distinguish cancellation from a network failure.
Forgetting await response.json() and logging the promise instead of the data is the most common fetch confusion. response.json() returns a promise because reading the body is asynchronous. Also remember CORS: a browser blocks reading a cross-origin response unless the server sends the right headers, and no client code can override that.
Write loadTitle(url, element) that fetches JSON, sets the element’s text to the title, and shows "Unavailable" with a console warning on any failure. Add a loading message before the request.
Show solution
Editable. Runs in your browser.
try {
const response = await fetch(url);
if (!response.ok) throw new Error("HTTP " + response.status);
const data = await response.json();
element.textContent = data.title;
} catch (error) {
element.textContent = "Unavailable";
console.warn(error.message);
}
}
const out = document.createElement("p");
document.body.append(out);
loadTitle("https://jsonplaceholder.typicode.com/todos/3", out);
Press Run to see the output.
The three states are explicit: loading, success and failure. The catch covers HTTP errors, network errors and parse errors, which all end with the same user-facing sentence.
Recap
fetchresolves for HTTP errors, so checkresponse.okand throw deliberately.- Read the body once with
response.json(); POST sends a stringified body and a content type. - Show loading, success and failure states, and use
AbortControllerfor timeouts.
Next, you will see what a promise is underneath await, and how to wait for several at once.
Why does fetch not reject on a 404?
How do I send credentials?
Progress is saved in this browser only. No account, no email.