JavaScriptadvanced 9 min
Get data from a server with fetch, read JSON, and handle errors and loading states.
How to request data with fetch, turn the response into a JavaScript object with .json(), check for errors, and send data with POST.
Most apps show data that lives on a server: posts, products, weather. An API (Application Programming Interface) is the doorway a server opens so your code can ask for that data. fetch is how the browser walks through it.
fetch(url) starts a request and returns a promise for a Response object. Then response.json() returns another promise with the parsed data.
Important details:
fetch only rejects on network failure. A server error such as 404 or 500 still gives you a response. Check response.ok (true for status 200 to 299) and handle it yourself.JSON.parse and JSON.stringify convert between text and objects.method: "POST", a headers object with "Content-Type": "application/json", and a body of JSON.stringify(data).data: URL so there is something to fetch without a network.loadUsers prints loading..., then awaits the response.response.ok. A bad status would throw and be caught below.response.json() turns the text into an array of objects.1 Asha (active) and 2 Ravi (inactive).try / catch makes sure any failure prints an error instead of crashing.For a real POST request you would write:
Add a third user to the JSON text, then print only the active users with .filter().
response.ok.await response.json(), so you get a promise instead of data.stringify when sending data.fetch returns a promise for a response; .json() gets the data.response.ok and handle errors.Next: modern JavaScript features that make code shorter.
const response = await fetch(url);
const data = await response.json();const json = JSON.stringify([
{ id: 1, name: "Asha", active: true },
{ id: 2, name: "Ravi", active: false },
]);
const url = "data:application/json," + encodeURIComponent(json);
async function loadUsers() {
try {
console.log("loading...");
const response = await fetch(url);
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
const users = await response.json();
for (const u of users) {
console.log(u.id, u.name, u.active ? "(active)" : "(inactive)");
}
} catch (err) {
console.log("error:", err.message);
}
}
loadUsers();await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Zoya" }),
});