In this article
You will get to know about...Introduction :
Axios is a promise-based HTTP Client for node.js and the browser. Axios is popular Javascript Library used for making HTTP Requests from the browser or Node.js
Whether you're building a web app or a server-side application, Axios makes it easy to work with API's and other HTTP services. On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.
In this post we will show you how to get started with Axios from installation to making basic GET and POST requests and handling errors, using asysc/await functions.
Features 📝
→ Make XMLHttpRequests from the browser.
→ Make http requests from node.js.
→ Supports the Promise API.
→ Intercept request and response.
→ Posting HTML forms as JSON etc.
Setting up Axios 📝
To start using Axios, you'll need to install it in your project. You can do this using NPM or a CDN.
Once you've installed Axiox, you can include in your HTML or Javascript code.
Using npm :
Using jsDelivr CDN :
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Performing a GET request
There are different ways to perform a request, 👇 let's make a simple GET request to retrieve data from an API, In our case we are going to use CDN
Method 1 :axios.get('https://dummyjson.com/products')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
Method 2 :
async function getUser() {
try {
const response = await axios.get('https://dummyjson.com/products');
console.log(response);
} catch (error) {
console.error(error);
}
}
In this code : 👆
→ We are using the async/await keywords to create asynchronous function and wait for the response from the API before logging the data in console.
Output :
In the console we are getting the below output 👇
NOTE : async/await is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution.
Performing a POST request
Now let's make a simple POST request to send data from an API, Here 👇 is an example how to make a POST request with Axios using async/await.
Example :axios.post('https://dummyjson.com/products/add', {
title: 'Club of Developers'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
The data we are sending is an object, if request is successful data will be logged in console.
Output :
Handling Errors
→ Http request can sometimes fail due to various reasons such as network errors or server-side errors.
→ It's important to handle these errors gracefully in our code.
→ Fortunately Axios provides several options to handle these errors and exceptions.
0 Comments