📜  javascript fetch json - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:05.134000             🧑  作者: Mango

Javascript Fetch JSON

In JavaScript, fetch is a powerful built-in function that allows you to make asynchronous HTTP requests. It is commonly used to retrieve JSON data from a server.

Fetching JSON Data

To fetch JSON data using fetch, you need to provide the URL of the JSON resource you want to retrieve. Here's an example:

fetch('https://api.example.com/data.json')
  .then(response => response.json())
  .then(data => {
    // Handle the JSON data here
    console.log(data);
  })
  .catch(error => {
    // Handle any errors that occur during the fetch
    console.error(error);
  });

In the above code, we first call the fetch function with the URL as the parameter, which initiates the HTTP request. The fetch function returns a Promise that resolves to the Response object representing the response to the request.

We then chain a .then() method to the returned Promise, which converts the response to JSON format using the json() method of the Response object. This also returns a Promise that resolves to the JSON data contained in the response.

Finally, we chain another .then() method to access the actual JSON data and perform any necessary operations on it. In this example, we simply log the data to the console. We also include a .catch() method to handle any errors that may occur during the fetch operation.

Error Handling

When using fetch to retrieve JSON data, it's important to handle any potential errors that may arise. This can be done using the .catch() method as shown in the previous example. Other error handling techniques like try-catch can also be used.

fetch('https://api.example.com/data.json')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

In the above code, we add an additional check before converting the response to JSON. If the response is not successful (status code indicating success is not in the range 200-299), we throw an error. This ensures that we only proceed to handle the JSON data if the fetch operation was successful.

Summary

Fetching JSON data in JavaScript using the fetch function is a common practice for making asynchronous HTTP requests. It allows you to retrieve data from a server in JSON format and perform various operations on it. Proper error handling should be implemented to handle any errors that may occur during the fetch operation.