Getting Started With Axios

Ryan Flynn
CodeX
Published in
3 min readJan 2, 2021

If you’ve ever needed to make a JavaScript HTTP Request you may have defaulted to using a classic fetch request. What you may have noticed though is that you have to constantly write out your headers, and parse through your data using things like JSON.stringify(). Axios is a third party HTTP client that simplifies this process by pre-parsing your data object. In this blog, I’ll show you how to make both a GET and POST request with Axios so you can simplify your requests.

Installing Axios

The first thing you are going to want to do is either install Axios using npm install axios or use the CDN link in your HTML: <script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>. Here’s a link to the documentation if you have any trouble with the installation.

Writing a Get Request

To write a GET request in Axios we first need to import our Axios library (I am using react, but if you use vanilla JS then use const axios = require(‘axios’);instead). After you’ve imported it all you have to do is simply call axios.get() with the link you are requesting data from. After that, you should call.then() , and you will have your response already! No need for any further parsing. This will give you a response with all the data you requested, the configuration, the headers, the type of request, and the request’s status.

Writing a Post Request

Writing a POST request is almost exactly like our GET request except all we need to do is pass in the object we want to add to our database.

It’s as simple as that!

Error Handling

This is the greatest part of Axios for me because it automatically helps you detect errors and subsequently catch them.

It’s literally that easy! If you’re requesting from an API or your backend and let’s say it gives you a status code of 400, it will automatically know that it should throw an error. This makes error handling much much faster.

Conclusion

And that’s it! You now know how to get started with Axios, and how it can be much simpler than XML or fetch requests. Thanks for reading!

Sources:

--

--