CodeX
Published in

CodeX

Getting Started With Axios

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 . 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 or use the CDN link in your HTML: . 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 instead). After you’ve imported it all you have to do is simply call with the link you are requesting data from. After that, you should call. , 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:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ryan Flynn

Full-Stack Engineer with a background in Javascript, React.js, React Native, Redux, Ruby, and Ruby on Rails.