Why Use Axios in Your Next App

When I was given 48 hours to make a CRUD Application, I found myself actively prowling through the various 475,000 packages on npm to find potential resources that would help solve oncoming problems, but I was soon lost within its collections.

Suddenly, the endless library of packages in the JavaScript ecosystem felt more of a curse when one doesn’t know how or where to find something. The key to well-designed libraries is that you only need a few of them to set you on track.

With that said, there is one library that helped greatly in building my app — axios!


axios

Promise-based HTTP client for the browser and node.js

The core of axios revolves around making intuitive and ensured HTTP requests from node.js or XMLHttpRequests from the browser by supporting the Promise API. Like fetch and superagent, it can work on your front-end application and your Node.js backend. By using axios, it simplifies asynchronous HTTP requests and performs CRUD operations in a very straightforward manner. The library can be used in vanilla JavaScript or with other advanced frameworks like Vue.js. Another key attribute is that axios performs automatic transformations for JSON data.

Below are a few examples of GET and POST requests.

GET requests

Using axios

axios.get('url')
.then((response) => {
console.log(response);
})
.catch((response) => {
console.log(error);
});

Without axios

let xhr = new XMLHttpRequest();
xhr.open('GET', 'url', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
(perform some code);
} else {
(handle error)
}
};
xhr.send();

POST request

Using Axios

  1. First argument: url
  2. Second argument: request body
  3. Third argument: configuration
  4. Handle response
axios.post( 'url',
{
contact: 'James',
email: 'james.h@gmail.com'
},
{
headers:{
'Content-type': 'application/json',
'Accept': 'application/json'
}
}
)
.then((response) => {
console.log(response.data);
})
.catch((response) => {
console.log('Error!)
});

Without Axios

let xhr = new XMLHttpRequest();

xhr.open('POST', 'url', true);

xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onreadystatechange = () => {
if (
xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
} else {
(handle error)
}
};
xhr.send();
Like what you read? Give Janelle Wong a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.