After this lesson you can load live data from the internet into your page. You will write a small fetch request, turn the reply into JavaScript data, deal with failure, and send data back.
You need async and await and, ideally, JSON. Everything in this lesson builds on them.
What fetch does
fetch(url) asks a server for something and returns a promise. When the server begins answering, the promise fulfils with a Response object. That object holds the status, the headers and the body. Reading the body is a second asynchronous step, because the data may still be arriving.
async function getTodo(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
const item = await getTodo(1);
console.log(item.title, item.completed); // delectus aut autem falseThe example uses a free practice API called JSONPlaceholder, which serves made-up data for learning. Its data could change one day, so do not rely on the exact text. The top-level await works in a module or in the browser console; in a normal script, wrap it in an async function.
Step by step:
fetch(...)sends a GET request, the default, andawaitwaits for the response headers.response.okistruefor status codes 200 to 299.response.json()reads the body and parses it as JSON. It also returns a promise, so wereturnit (an async function waits for it) orawaitit.
Other readers exist for other data: response.text() for plain text or HTML, and response.blob() for files such as images.
Try it
Press Try it, then run the code. It fetches a to-do item and shows the fields. The preview is an isolated frame, but this API allows requests from it.
<p id="status">Loading...</p>
<pre id="out"></pre>
<script>
const statusLine = document.getElementById("status");
const out = document.getElementById("out");
async function getTodo(id) {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/" + id);
if (!response.ok) throw new Error("Request failed with status " + response.status);
return response.json();
}
async function show(id) {
try {
const item = await getTodo(id);
statusLine.textContent = "Loaded";
out.textContent = "title: " + item.title + "\ncompleted: " + item.completed;
} catch (error) {
statusLine.textContent = "Something went wrong: " + error.message;
}
}
show(1);
</script>You should see Loaded, then title: delectus aut autem and completed: false. Change show(1) to show(99999). That item does not exist, the server answers 404, and the page shows Something went wrong: Request failed with status 404. Switch your device offline and the message will be about a failed network request instead.
Two kinds of failure
This is the most important thing to remember about fetch:
- A network failure (no connection, a bad domain, blocked by CORS) rejects the promise with a
TypeError. The message depends on the browser, for example "Failed to fetch" in Chrome. - An HTTP error status (404, 500 and so on) is not a failure as far as
fetchis concerned. The promise fulfils normally, andresponse.okisfalse.
So always check response.ok or response.status, as the examples do, and wrap the whole thing in try/catch. Forgetting this leads to the confusing situation where your await response.json() fails on an error page, long after the real problem.
Sending data with POST
Pass a second argument, an options object, to change the method and add a body.
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json; charset=UTF-8" },
body: JSON.stringify({ title: "hello", body: "world", userId: 1 }),
});
console.log(response.status); // 201
console.log(await response.json()); // { title: 'hello', body: 'world', userId: 1, id: 101 }The body must be a string, so use JSON.stringify. The Content-Type header tells the server it is JSON. This practice API pretends to save your post and answers with status 201 ("created") and an id, but nothing is really stored.
Building a query string
Parameters after a ? in the URL are the query string. URLSearchParams builds one and handles special characters for you:
const params = new URLSearchParams({ userId: 1, _limit: 2 });
console.log(String(params)); // userId=1&_limit=2
const response = await fetch("https://jsonplaceholder.typicode.com/todos?" + params);
const todos = await response.json();
console.log(todos.length); // 2Several requests at once
Independent requests should run together:
const [a, b] = await Promise.all(
[1, 2].map(id =>
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(r => r.json())
)
);
console.log(a.id, b.id); // 1 2Loading, success and error states
Real pages should show the user what is happening. A request has three phases, and each deserves a message: loading ("Loading..."), success (the data) and error (a calm explanation and a way to retry). The try-it example above does that with its status line. Also disable the submit button while a POST is in flight, so a double click does not send it twice.
You can cancel a request with an AbortController. Pass { signal: controller.signal } to fetch, and call controller.abort(). The pending promise then rejects with an error whose name is AbortError. That is useful when a user types a new search before the old one finished.
CORS in plain words
Browsers protect users with the same-origin policy: a page on one site is not allowed to read responses from another site unless that site agrees. The agreement is a response header, Access-Control-Allow-Origin. If it is missing, your fetch fails with a network error and the console mentions CORS, even though the server did answer.
You cannot fix this from the front end. Either the API's owner has to allow your origin, or you call it through your own server. It is the server's job, not something to work around with a library. Public practice APIs generally allow all origins. A request to your own site or localhost is same-origin and not affected.
Secrets belong on a server. Never put an API key that must stay private in front-end JavaScript, because anyone can open the Network panel (see Debugging with the browser tools) and read it.
Common mistakes
- Not checking
response.ok. A 404 or 500 page then flows into your code as if it were data. - Forgetting to
await response.json(). You get a promise, not the data. - Forgetting
JSON.stringifyfor POST. Sending an object directly gives the text[object Object]. - Missing the
Content-Typeheader. The server may not understand the body. - Reading the body twice. A response body can be read only once. Call
response.clone()first if you really need two reads. - Treating CORS as a bug in your code. It is a server setting; check the Network panel for the real status and headers.
- No loading or error message. To the user, a silent page looks broken.
- Hard-coding secrets in front-end code. Anyone can read them.
You can paste a response into the JSON formatter to make it easier to read while you work out its shape.
Exercise
Write async function loadTodos(limit) that fetches https://jsonplaceholder.typicode.com/todos?_limit= followed by the limit, checks response.ok, and returns the array. Use it to put each title into a list on the page, with "Loading..." shown first and an error message in a catch. Then change the URL to a non-existent path such as /todoz to confirm your error message appears.
Next, the final section: organise code into files with Modules: import and export.
Key points
- fetch(url) returns a promise for a Response, and response.json() returns another promise for the parsed data.
- fetch only rejects on network failure; a 404 or 500 still resolves, so check response.ok yourself.
- To send data, pass method, headers and a JSON.stringify body in the options object.
- A good request has three states to show the user: loading, success and error.
- Browsers block cross-origin responses unless the server allows them with CORS headers, and that cannot be fixed from your page.