Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Load a JSON File With fetch()

In this video, you moved Sam’s starter recipes out of main.js into a data file, since they’re data, not code, and Sam can now fix a step without touching main.js. You loaded them with fetch(), and saw why the code has to check the server’s answer before it reads the file.

Key Points

  • A page asks its server for a data file. The page came from Live Preview’s server, not from your disk, so it can’t read the file directly. fetch("data/recipes.json") asks the server for it, as the page does for every file it loads. The path starts from the page’s folder, so the file goes in a data folder next to index.html.
  • await waits for the answer. At the top level of a module, await in front of fetch() makes main.js wait there until the server answers, and the rest of main.js waits too. The page doesn’t freeze while it does. Why that works comes later.
  • First the answer, then the body. fetch() gives back a Response, the server’s answer, not the data yet. Its status is a number, 200 when the server found the file. Its ok is true for any success status, 200 to 299, and false otherwise. ok says nothing about what’s in the file, so it’s true even when the file’s JSON is broken. The answer can arrive before all of its body, so reading the body takes a second await: response.json() reads it and parses it, as JSON.parse() does.
  • The Network panel shows the request. With the Fetch/XHR filter, which hides the page’s other files, a reload shows one row for recipes.json with status 200. Click it, and its Response tab shows the body, which is your file’s text. The page doesn’t draw the recipes’ steps yet. If your box has saved recipes, the page shows those instead of the starters; open it in a private window to see the four starters.
  • A 404 doesn’t make fetch() throw. With the path one letter off, data/recipe.json, the server answers with a 404, and an answer is still a Response, with ok set to false. The log line after fetch() still ran and showed 404 false. The red line in the Console is the browser reporting the failed request, not an error in your code. fetch() throws when the request can’t finish, for example when there’s no server.
  • The error that does come blames the JSON. Reading the body threw SyntaxError: Unexpected token '<' … is not valid JSON, because the body was Live Preview’s File not found page, in HTML, and the < is where that page starts. A catch around these lines would get the same misleading error. The real problem is the file name.
  • The rule: fetch() hands you the server’s answer, even when that answer is no. Check response.ok, then read the body. When ok is false, throw a new Error() whose message names the file and the status. new Error() makes an error object like the ones a catch receives, and throw stops the code with it.
  • The error names the real problem. With the typo, the Console then says Uncaught Error: Couldn't load data/recipe.json: status 404. The box still stops. The form is there, but the list stays empty and nothing works, and only the Console says why. You’ll show the problem on the status line later in the course.

The Code

Open Sam’s recipe box through Live Preview at http://127.0.0.1:3000/recipes/index.html. Make a folder called data inside recipes, next to index.html, and save this as recipes/data/recipes.json:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In this video, Sam’s recipe box loads its starter recipes from a file. They sit at the top of main.js. But they’re data, not code. In their own file, Sam can fix a step without touching main.js.

00:15 So they move into recipes.json, in a new data folder next to index.html. It holds four recipes with steps for the timers, one of them new: Soft-boiled eggs.

00:26 Stop the video and copy it from below.

00:30 The page can’t read your disk. It asks Live Preview’s server for the file, as it does for every file it loads.

00:39 At the top of main.js, add two lines. The first passes the path data/recipes.json to fetch, the browser’s function that asks the server for a file. The path starts from the page’s folder.

00:54 The await in front makes main.js wait there for the server’s answer, but the page doesn’t freeze. Why that works comes later. That’s all you need about await for now.

01:05 fetch gives back a Response, the server’s answer, not the recipes yet. The second line logs two things: its status code, and ok. Save, and the Console shows 200 true.

01:19 Status 200 means the server found the file. ok is true for any success status, 200 to 299, even for broken JSON.

01:30 The recipes are in the Response’s body. In the Network panel, pick the Fetch/XHR filter, which hides the page’s other files, and reload. Click the recipes.json row, then its Response tab, which shows the body, your file’s text.

01:47 Replace the whole array with one line. It awaits response.json(), which reads the body and parses it, as JSON.parse does. The body can arrive after the answer, so it needs a second await.

02:01 Save. Sam’s box has no saved recipes yet, so it shows the starters, four now, including Soft-boiled eggs. The page doesn’t draw their steps yet. With saved recipes, you’ll see yours instead.

02:15 A private window shows the starters.

02:19 Now make a common slip: drop the s, so the path says recipe.json. There’s no such file. Your turn. Pause the video and predict: does the log line after fetch still run?

02:38 It does, and it shows 404 false.

02:43 The red line above is the browser logging the failed request, not your code failing.

02:49 So fetch didn’t throw. A 404 is the server’s answer for a missing file, and an answer is still a Response, with ok false. fetch throws when the request can’t finish, say with no server, as the next lesson shows.

03:06 Something did throw. It’s the last red line in the Console. Reading the body threw a SyntaxError: the text isn’t valid JSON. The recipe.json row in the Network panel shows why.

03:19 Its Response tab holds Live Preview’s File not found page, and the error trips over its first less-than sign. A catch around these lines would get the same misleading error.

03:30 The real problem is the file name.

03:33 To fix it, check the answer before you read the body. Keep the path in a constant named path, so the error can name it. Then replace the log line with an if: when ok is false, throw a new Error naming the file and the status.

03:49 new Error makes an error object like the ones a catch receives. throw stops the code with it. Save with the typo, and the Console says: Couldn’t load data/recipe.json: status 404.

04:05 The box still stops. Its form does nothing. Now the error names the real problem. Showing it on the status line comes later. Put the s back, and the four starters return.

04:17 The rule: fetch hands you the server’s answer, even when that answer is no. Check response.ok, then read the body. Next, in Load a CSV File, you’ll load Ayumi’s list as text and see what happens with no server at all.

Become a Member to join the conversation.