JavaScript

How to install and use Axios in JavaScript

Building a real-world application often requires interaction with APIs to send and fetch data; there are multiple ways of interacting with APIs. One of the packages that allow JavaScript as well as NodeJs projects to interact with APIs with very simple and straightforward code syntax is Axios.

Axios is an HTTP client, which is used to make XMLHttpRequest from the browser as well as HTTP requests for projects created with NodeJS. It is often referred to as the isomorphic HTTP client, where isomorphic means for both NodeJs and browsers(vanilla JavaScript).

Axios provides methods like get, post, and delete and automatically transforms the JSON data which is something that sets it apart from the trivial JavaScript methods like the fetch() method from the Fetch API.

Installing Axios in JavaScript

As already mentioned above, Axios is present for the browser as well as the node environment, which means that it can be installed with npm and in Vanilla JavaScript using the CDN-hosted Axios script. There are multiple ways of installing Axios JavaScript in your project such as:

Using the node package manager (npm)

Axios is available to the npm library and can be easily installed in the project by running the following command in the terminal of your code editor:

$ npm install axios

Using bower to install Axios

Bower is increasingly getting more and more famous among the masses. Bower helps install web packages just like npm. If you are working with bower, then you can install Axios by using the following lines of code:

$ bower install axios

Using a CDN hosted Axios

CDN stands for content delivery networks, these networks allow you to use JavaScript libraries hosted on their servers. Axios can be installed in your project by using one of the two CDN Axios providers, the first being “JsDelivr CDN” and the other one being the “unpkg” CDN.

For JsDelivr CDN use the command in your HTML file:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

For the unpkg CDN use the command HTML file:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

With these above mentioned commands you should be able to install and use Axios in your projects.

Using Axios in JavaScript

To demonstrate the usage of Axios that we have just installed by using one of the methods mentioned above in a JavaScript program, we are going to need an HTML webpage. For this post, we are going to write the following lines inside the HTML file:

<center>

<div>

<h3>Users</h3>

<ul></ul>

</div>

</center>

As you can notice in the code, we have made an unordered list which we will use to display the list of users we get from the API.

This should give us the following webpage on our browser:

To demonstrate the fetching of data using the Axios, we are going to be using the REQ | RES API and the URL for the API is “https://reqres.in/api/users”. The next step is to write three different functions in our JavaScript file:

  • fetch_Users(): This will use Axios to get data from the API and send the data to appendToDOM() function
  • appendToDOM(): This will add the user’s name to the <ul> tag after creating a new list item with the help of the create_Li function
  • create_Li(): This will take each user’s data and create a new list item with only the name of the user placed inside it:

The fetch_user() function looks like this:

const fetch_Users = () => {
axios.get("https://reqres.in/api/users").then((response) => {
      const users = response.data.data;
appendToDOM(users);
    })
    .catch((error) =>console.error(error));
};

The appendToDom() function can be created with the following lines:

const appendToDOM = (users) => {
  const ul = document.querySelector("ul");
users.map((user) => {
ul.appendChild(create_Li(user));
  });
};

And lastly, the create_Li() function can be created using the following lines of code:

constcreate_Li = (user) => {
const li = document.createElement("li");
li.textContent = `${user.id}: ${user.first_name} ${user.last_name}`;
return li;
};

Now that we have coded all of our functions, we only have to invoke the fetch_Users function, but for that we are going to add a button in our HTML file with the following lines of code:

<button id="button">Click me to get Data</button>

Now that we have our button, we can execute the fetch_Users() function upon the button press using the following code in our script file:

$("#button").click(function () {

fetch_Users();

});

The Complete HTML Code is as:

<center>

<div>

<h3>Users</h3>

<ul></ul>

<button id="button">Click me to get Data</button>

</div>

</center>

The complete JavaScript code is as:

$("#button").click(function () {
fetch_Users();
});

constcreate_Li = (user) => {
const li = document.createElement("li");
li.textContent = `${user.id}: ${user.first_name} ${user.last_name}`;
return li;
};

constappendToDOM = (users) => {
const ul = document.querySelector("ul");
users.map((user) => {
ul.appendChild(create_Li(user));
  });
};

constfetch_Users = () => {
axios
    .get("https://reqres.in/api/users")
    .then((response) => {
const users = response.data.data;
appendToDOM(users);
    })
    .catch((error) =>console.error(error));
};

On running this code, you will get the following result on your browser:

As you can see, we are able to fetch data from the API upon button press using Axios in our javascript code.

Conclusion

Axios is an isomorphic HTTP client that is available for both the node development environment and for the vanilla JavaScript. Axios is a strictly Promise-based library, and automatically converts the data that it fetches from the API from JSON format. To use Axios in your project, you need to either install it from the npm library or add it in your HTML file by using a CDN hosted by Axios. In this post, we learned how to install and run axios in our javascript project.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.