Fetch API and JSON
Level 5 · JavaScript in the page
How a page asks a server for data without loading a new page. Using fetch with await, reading JSON, and checking that the reply was not an error.
Course contentsLesson 13 of 14
Level 1 · How a website works
Level 3 · CSS basics
Level 4 · Page layout
Level 5 · JavaScript in the page
After this lesson you can
- Request data with fetch and await
- Read a JSON reply into JavaScript
- Check the status before using the data
13 mincovers 4 glossary entries
Worth reading first: JavaScript and the DOM
How a page gets data from a server
The Fetch API is how code in a web page asks a server for data. You call fetch() with an address, and it sends the request while the page keeps working. The reply usually comes back as JSON. A reply with status code 200 to 299 is a success, and response.ok is true.
A fetch takes time, from a blink to several seconds. JavaScript does not stop and wait. fetch() hands back a promise, which stands for a result not ready yet. Writing await in front of it pauses only that one function until the reply comes. Clicks and scrolling go on.
JSON is a plain text format for data made of names and values. It looks like {"temp": 18, "city": "London"}. The names are always in double quotes. Calling response.json() reads that text and turns it into a normal JavaScript object, so data.temp gives you 18.
Every reply carries a status code, a three-digit number that says how the request went. 200 means it worked. 404 means the address was not found, and 500 means the server broke. The surprise is that fetch counts a 404 or a 500 as a reply, not a failure.
So fetch only throws an error when the request never got a reply at all, such as when the network is down. A 404 page comes back quietly and your code reads it as if it were the data. Always check response.ok, and stop when it is false.
A page can also send data. Give fetch a second input with method: "POST" and a header that says the body is JSON. Then add the body, turned into JSON text. The server reads it much like a form, and the page does not reload.
People often call fetch on a different site and are surprised when it is blocked. Browsers stop a page from reading another site's replies unless that site says yes. The usual fix is to call your own server, and let it call the other site.
async function showWeather() {
const response = await fetch("/api/weather?city=London");
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
const data = await response.json(); // { "temp": 18 }
document.querySelector("#temp").textContent = data.temp + "°C";
}Worked example
Jack's app shows undefined degrees
Jack's weather page sometimes shows undefined°C. The server returns a 404 for a city it does not know, and his code reads the error page as data.
He adds a check on response.ok. Now an unknown city shows a clear message, and only a 200 reply reaches the screen.
The words for this lesson4
Check yourself
Does fetch throw an error when the server replies 404?
Finished this lesson?
Marking it complete also marks its 4 glossary entries learned, which updates your roadmap and your saved page. 0 are already marked.