Home  >  Article  >  Web Front-end  >  How to get data using JavaScript Fetch API?

How to get data using JavaScript Fetch API?

WBOY
WBOYforward
2023-08-24 17:13:021140browse

如何使用 JavaScript Fetch API 获取数据?

Nowadays, JavaScript is very useful for writing front-end and back-end code. Furthermore, it is also the most widely used programming language.

Also, we need to get data from other servers when developing real-time applications. We can use API (Application Programming Interface) to get data from other servers or databases.

Here, we will learn various ways to get data using JavaScript.

Use fetch() method

fetch() is the method used by the browser to obtain data from the API. It takes the API URL as the first parameter we need to get the data from and the options as the second parameter. These options can contain headers and authentication tokens.

grammar

Users can use the following syntax to fetch() to obtain data.

fetch(baseURL)
.then(data => {
   // use data here
}

In the above syntax, baseURL is an API for obtaining data.

Example 1

In the example below, when the user clicks the button, it executes the fetchData() function. In the fetchData() function, we use the fetch() method to get the data from the API. After that, we handled responses and errors. Users can see the data we get from the API in the output.

<html>
<body>
   <h2>Using the <i> fetch() browser method </i> to fetch data from API</h2>
   <div id = "output"> </div> 
   <button onclick = "fetchData()"> Fetch API to get data </button>
   <script>
      let output = document.getElementById('output');
      function fetchData() {
         fetch('https://dummyjson.com/products/1')
         .then(response => response.json())
         .then(data => {
            output.innerHTML += "id = " + data.id + "<br/>";
            output.innerHTML += "brand = " + data.brand + "<br/>";
            output.innerHTML += "category = " + data.category + "<br/>";
            output.innerHTML += "price = " + data.price + "<br/>";
            output.innerHTML += "rating = " + data.rating + "<br/>";
            output.innerHTML += "stock = " + data.stock + "<br/>";
         })
      }
   </script>
</body>
</html>

Using axios npm package

axios is an NPM package that allows developers to interact with APIs by making requests such as GET, POST, PUT, etc. Here, we will use axios to make a GET request to get the data in JavaScript.

grammar

Users can use axios to get data from the API according to the following syntax.

axios.get(URL)
.then((response) => {
   // use response
} 

In the above syntax, we use the axios.get() method to get data from the API.

Example 2

In this example, we resolve the Promise using then() and catch() blocks obtained from the server or database. We exploit the data in the then() block and the error in the catch() block.

<html>
<head>
   <script src ="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"></script>
</head>
<body>
   <h2>Using the <i> Axios NPM package </i> to fetch data from API</h2>
   <div id = "output"> </div>
   <button onclick = "fetchData()"> Fetch data using Axios </button>
   <script>
      let output = document.getElementById('output');
      function fetchData() {
         axios.get("https://jsonplaceholder.typicode.com/todos/1") 
         .then((response) => {
            output.innerHTML += "userId : " + response.data.userId + "<br/>";
            output.innerHTML += "id : " + response.data.id + "<br/>";
            output.innerHTML += "title : " + response.data.title + "<br/>";
            output.innerHTML += "completed : " + response.data.completed + "<br/>";
         })
         .catch((err) => {
            output.innerHTML += "The error is - " + err + "<br/>";
         })
      }
   </script>
</body>
</html>

Example 3

In the following example, we use axios to get data through async/await syntax. We have made the getData() function async. Additionally, we have used the await keyword in axios to pause the execution of the function until we get a response from the API.

<html>
<head>
   <script src ="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"></script>
</head>
<body>
   <h2>Using the <i> Axios NPM package </i> with Async/await syntax to fetch data from API</h2>
   <div id = "output"> </div>
   <button onclick = "getData()"> get data using Axios </button>
   <script>
      let output = document.getElementById('output');
      async function getData() {
         let response = await
         axios.get("https://jsonplaceholder.typicode.com/todos/1")
         for (let key in response.data) {
            output.innerHTML += key + " - " + response.data[key] + "<br/>";
         }
      }
   </script>
</body>
</html>

Using XMLHttpRequest Web API

XMLHttpRequest Web API allows us to create modules to get data. We can create an object and initialize it using XMLHttpRequest. We can then use this object to open a GET request.

After that, we can call the callback function when XMLHttpRequest is loaded. The callback function can get the response status and return the response or error accordingly.

grammar

const xmlRequest = new XMLHttpRequest();
xmlRequest.open('GET', apiURL);
xmlRequest.responseType = 'json';
xmlRequest.onload = function () {
   // handle the response from API
}
xmlRequest.send(); 

In the above syntax, we first open the request using the open() method, and then use the onload event to handle the response from the API.

Example 4

In the following example, we have to create a custom module using XMLHttpRequest() Web API to get data from the API. The customRequest() function contains custom modules.

Afterwards, we call the customRequest() function by passing the URL as a parameter and use a then() block to resolve the Promise returned from the customRequest() function.

<html>
<body>
   <h2>Using the <i> XMLHttpRequest web API </i> to fetch data from API</h2>
   <div id = "output"> </div>
   <button onclick = "getData()"> get data </button>
   <script>
      let output = document.getElementById('output');
      const customRequest = (apiURL) => {
         return new Promise((res, rej) => {
      
            // Create a new Object of XMLHttpRequest
            const xmlRequest = new XMLHttpRequest();
            
            // open a get request
            xmlRequest.open('GET', apiURL);
            
            // set response type
            xmlRequest.responseType = 'json';
            xmlRequest.onload = function () {
               // resolve the promise when we get a successful response
               if (xmlRequest.status == 200) {
                  res(xmlRequest.response);
               } else {
                  
                  // reject promise on error
                  rej(xmlRequest.response);
               }
            };
            
            // send request
            xmlRequest.send();
         }); 
      };
      
      // making the get request from URL
      const getData = async () => {
         try {
            const data = await customRequest(
               'https://dummyjson.com/products/1',
            );
            output.innerHTML += "category = " + data.category + "<br/>";
            output.innerHTML += "price = " + data.price + "<br/>";
            output.innerHTML += "rating = " + data.rating + "<br/>";
            output.innerHTML += "stock = " + data.stock + "<br/>";
         } catch (err) {
            output.innerHTML += "The error is : " + err + "<br/>";
         }
      };
   </script>
</body>
</html> 

We learned three different ways to get data from the API. The best way is to use the fetch() method of the browser as we don't need to install any module to use it. Additionally, users should use all modules with async/await syntax.

The above is the detailed content of How to get data using JavaScript Fetch API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete