Axios is a HTTP client for the browser and Node.js . It helps you connect your frontend app with an external server or API easily. In this tutorial , we will learn how to install Axios , make GET and POST requests , and handle errors using basic examples .
How to Use Axios JavaScript Library
When u are building websites or web applications or later you will need to talk to a server for fetching some data into it , submit a form , update something in the database . In JavaScript the fetch() function is commonly used , but its sometimes really complicated to understand when handling errors or working with complex data.
Axios is a small JavaScript library that helps you send HTTP requests (like GET and POST) which is easy to understand.
You can add Axios using a simple CDN link in your HTML file , or install it using npm if you are working on a bigger project .
To Add Axios – we include it into your HTML file using this script.
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Now after this script is added , you can start writing Axios right away in your <script> tags.
Making a GET request.
<script> axios.get('https://jsonplaceholder.typicode.com/posts/1') .then(function(response) { console.log(response.data); }) .catch(function(error) { console.log("Something went wrong:", error); }); </script>
This code sends a request to post number 1 , if sucessful it logs the data in your browser console , if there is an error it shows a message.
Making a Simple POST Request.
<script> axios.post('https://jsonplaceholder.typicode.com/posts', { title: 'Hello Axios', body: 'This is a test post', userId: 101 }) .then(function(response) { console.log("Post created:", response.data); }) .catch(function(error) { console.log("Error creating post:", error); }); </script>
This code sends the title , body , userId to the server . Used to sendd user input from a form.
Handling Errors.
<script> axios.get('https://wrongurl.typicode.com/data') .then(function(response) { console.log(response.data); }) .catch(function(error) { console.log("There was an error:", error.message); }); </script>
Axios is a very helpful library , especially if you are new to working with APIs in JavaScript , It reduces the amount of code you need to write , and it handles errors and JSON conversion for you.