Chapter Eleven · Input and Data
Talking to Servers
How a page asks a server for data and keeps working while it waits: promises and await, fetch and the response it returns, the site's projects loaded from a file, the rule that stops one site reading another, and live data from a real API with a plan for every way it can fail.
So far every piece of the site's content has been written into its own files. Real pages also show things that live elsewhere and change without them: prices, forecasts, messages, a list of someone's latest work. Getting that data means asking a server and waiting for an answer that may be slow, may be refused, or may never come. This chapter is about asking well, waiting without freezing the page, and telling the visitor the truth whatever the answer is.
Five topics. Why a page cannot simply stop and wait, and how promises with async and await let one function pause while the page carries on. fetch, the response it returns, and why a "not found" answer is not an error. The site's projects moved out of the code into a data file of their own, loaded with the site's first real request. The same-origin policy and CORS, the rule that keeps one site from reading another and the header that relaxes it. And live repositories from GitHub's public API on the Projects page, with loading, empty and error states, a missing field handled on purpose, and the rule that nothing in a page is secret.
Topics in This Chapter
async and await pause one function and not the page, and where to catch a failure.fetch and the response it returns, reading the body with a second await, and why a 404 is an answer you check with response.ok.data/projects.json, loaded with loadProjects(), with a loading message and an honest error when the file is broken.