API call in JavaScript using Axios
Axios is an open-source library for making HTTP requests to servers. It is a promise-based approach. It supports all modern browsers and is used in real-time applications. It is easy to install using the npm package manager.
It has better error handling than the fetch() method. Axios also does automatic transformation and returns the data in JSON format.
Example: In this example, Axios is used to make an API call.
Javascript
import axios from 'axios' ; axios.get( 'APIURL' ) .then(response => { // Access the response data const responseData = response.data; // Process the response data here }) . catch (error => { // Handle any errors }); |
Explanation: While sending the HTTP request it will respond to us with the error or the data which is already parsed to JSON format(which is the property of Axios). We can handle data with the .then() method and at the end we will use .catch() method to handle the error.
Note: Here we have to pass the URL and unlike fetch or XMLHttpRequest, we cannot pass the path to the resource.
4 Ways to Make an API Call in JavaScript
API(Application Programming Interface) is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data, and interact with each other. API is a service created for user applications that request data or some functionality from servers.
To give specific access to our system to other applications that may be useful to them, developers create APIs and give them endpoints to interact and access the server data. While working with JavaScript it is common to interact with APIs to fetch data or send requests to the server.
4 Ways to Make an API Call in JavaScript:
Table of Content
- API Call in JavaScript Using XMLHttpRequest
- API Call in JavaScript Using the fetch() method
- API call in JavaScript using Axios
- API call in JavaScript Using the jQuery AJAX