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 id="Using-the-i-fetch-browser-method-i-to-fetch-data-from-API">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 id="Using-the-i-Axios-NPM-package-i-to-fetch-data-from-API">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 id="Using-the-i-Axios-NPM-package-i-with-Async-await-syntax-to-fetch-data-from-API">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 id="Using-the-i-XMLHttpRequest-web-API-i-to-fetch-data-from-API">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!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
