How to Use the JavaScript Fetch API to Get JSON Data

In How to Use JSON Data with PHP or JavaScript, I discussed how to use XMLHttpRequest() to get data from a JSON feed.

The Fetch API is a newer built-in feature of JavaScript that makes working with requests and responses easier.

// Replace ./data.json with your JSON feed
  .then(response => {
    return response.json()
  .then(data => {
    // Work with JSON data here
  .catch(err => {
    // Do something for an error here

Note that with Fetch, even a 404 or 500 error will not return an error. Only a network error or a request not completing will throw an error.

No comments?

There are intentionally no comments on this site. Enjoy! If you found any errors in this article, please feel free to edit on GitHub.