Fetch High Scores

In this lesson, you will put your knowledge of asynchronous JavaScript to practice by fetching the high scores from a local web server.

We'll cover the following

Now that we have created our high scores locally in the browser, we can look at how to make a high score list open for all. For this, we need to move the scores from our computer to a server somewhere where they can be accessed.

For testing purposes, it’s often a good idea to start by making the data available locally. We can do this by creating a JSON file with the data. Since we can use fetch to get the data from the JSON, just like we would do with a remote call, it will be easy to replace the URL from local to remote.

We can’t use fetch directly on the file system, so we need to run a webserver to serve our file.

Prerequisites

Node.js with npm needs to be installed.

Http-server

The simple, zero-configuration command-line http-server can be run with:

npx http-server

It serves files from the folder we run the command from.

Npx is a tool for executing Node packages. If we use the npm package frequently, we can instead install it globally on our computer:

npm install -g http-server

Then, we can start it with:

http-server

Whichever way we use it, when the server starts, it tells us the address of where to run the game:

Now that we are serving the file, we can start the actual coding.

Fetch

First, create an empty file, highScores.json, where we can save the data.

Next, we change showHighScores() to an async function. Then, we change the code that get the high scores from local storage to instead fetch them from the JSON file:

async function showHighScores() {
  const highScores = await fetch('highScores.json')
    .then((response) => response.json())
    .catch((error) => console.log(error))
  || [] // Default if file is empty;

  // ...
}

The response from fetch is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method.

Running this code retrieves the high scores from the local file.

Next steps

We have now come as far as we can in working with our high scores in the frontend. If we want to save the high scores on a server somewhere, we can’t do it with fetch without writing some backend code.

The good news is that you can still use JavaScript with Node.js, using a framework like Express for example.

Finally, the last part of the puzzle before becoming a full-stack developer is to learn about databases to be able to save your high scores there instead of just a file.

Get hands-on with 1000+ tech skills courses.