How to get data using 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
