# How to use Axios to make HTTP requests in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 11, 2019, updated Oct 5, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/axios-javascript

> A practical guide to learning how to use the Axios library in JavaScript to make different HTTP requests.

Axios is an open-source library for making [asynchronous HTTP requests](https://attacomsian.com/blog/http-requests-axios) to REST endpoints in the browser and Node.js. It is a [promise-based](https://attacomsian.com/blog/promises-javascript) HTTP client that can be used in plain JavaScript and in modern JavaScript frameworks like React, Angular and Vue.js, etc.

In this tutorial, we will be using Axios in a JavaScript and HTML5 project. Let's create a new HTML5 project:

```bash
# create and switch to new directory
$ mkdir axios-js && cd axios-js

# create files
$ touch index.html script.js

# open the project in VS Code
$ code .
```

## Installation

Adding Axios to the HTML5 project is easy. You can use the npm package manager or Content Delivery Network (CDN). If you prefer to use the npm package manager, run the following command in your terminal:

```bash
$ npm install axios --save
```

It will download the library in the `node_modules` folder from where you can add it to your project:

```markup
<script src="./node_modules/axios/dist/axios.min.js"></script>
```

The easiest way to include Axios is by using an external CDN:

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

## User Interface

Let us update our `index.html` file to display a list of users:

<p class="file-desc"><span>index.html</span></p>

```markup
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Axios in JavaScript</title>
    </head>
    <body>
        <div>
            <h1>Users</h1>
            <ul></ul>
        </div>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>
```

For running the project, we will be using [http-server](https://www.npmjs.com/package/http-server) - a simple, zero-configuration command-line HTTP server:

```bash
$ http-server -p 3000
```

Now you can visit http://localhost:3000 to view your project.

## GET Request

Let us create a new function in the `script.js` file to fetch a list of users using the GET request. We will use [Reqres REST API](https://reqres.in) for all our examples.

<p class="file-desc"><span>script.js</span></p>

```javascript
const fetchUsers = () => {
  axios
    .get('https://reqres.in/api/users')
    .then(response => {
      const users = response.data.data
      console.log(`GET list users`, users)
    })
    .catch(error => console.error(error))
}

fetchUsers()
```

If you have used jQuery before, understanding the `axios.get()` function is easy. We just pass the endpoint URL as a parameter to this method. The method returns a [promise](https://attacomsian.com/blog/promises-javascript), allowing us to use `then()` and `catch()` methods to handle the result. 

When the promise is resolved successfully, you will get a `response` object back. This object has information about the response, such as `headers`, `data`, `config`, `status`, and even a complete `request` object.

Now let us extend our `script.js` file and add a new function that parses the `users` object and add it to DOM:

<p class="file-desc"><span>script.js</span></p>

```javascript
const createLi = user => {
  const li = document.createElement('li')
  // add user details to `li`
  li.textContent = `${user.id}: ${user.first_name} ${user.last_name}`
  return li
}

const appendToDOM = users => {
  const ul = document.querySelector('ul')
  //iterate over all users
  users.map(user => {
    ul.appendChild(createLi(user))
  })
}

const fetchUsers = () => {
  axios
    .get('https://reqres.in/api/users')
    .then(response => {
      const users = response.data.data
      console.log(`GET list users`, users)
      // append to DOM
      appendToDOM(users)
    })
    .catch(error => console.error(error))
}

fetchUsers()
```

## POST Request

We can add a new user to our REST API with the `axios.post()` method. Just add a new function `createUsers()` inside of `script.js`:

```javascript
const createUser = user => {
  axios
    .post('https://reqres.in/api/users', user)
    .then(response => {
      const addedUser = response.data
      console.log(`POST: user is added`, addedUser)
      // append to DOM
      appendToDOM([addedUser])
    })
    .catch(error => console.error(error))
}
```

To create a new user, you need to add a `<form>` inside the `index.html` file to capture user information:

```markup
<div id="create-user">
    <h1>Create User</h1>
    <form>
        <input type="text" id="first_name" placeholder="Enter First Name">
        <input type="text"  id="last_name" placeholder="Enter Last Name">
        <button type="submit">Add User</button>
    </form>
</div>
```

Now add an event listener for form submission to create a new user:

```javascript
const form = document.querySelector('form')

const formEvent = form.addEventListener('submit', event => {
  event.preventDefault()

  const first_name = document.querySelector('#first_name').value
  const last_name = document.querySelector('#last_name').value

  const user = { first_name, last_name }
  createUser(user)
})
```

## DELETE Request

Axios provides `axios.delete()` method to make a DELETE request. Let's add the delete feature to our users' list. First of all, create a new function `deleteUser()` inside of `script.js`:

```javascript
const deleteUser = (elem, id) => {
  axios
    .delete(`https://reqres.in/api/users/${id}`)
    .then(response => {
      console.log(`DELETE: user is removed`, id)
      // remove elem from DOM
      elem.remove()
    })
    .catch(error => console.error(error))
}
```

Now update the `createLi()` method to [attach](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) an `onclick` event which handles the removal of the user when clicked:

```javascript
const createLi = user => {
  const li = document.createElement('li')
  // add user details to `li`
  li.textContent = `${user.id}: ${user.first_name} ${user.last_name}`

  // attach onclick event
  li.onclick = e => deleteUser(li, user.id)

  return li
}
```

> **Source code:** Download the complete source code from [GitHub](https://github.com/attacomsian/code-examples/tree/master/others/axios-js) available under MIT license.

## Summary

Axios is a simple-to-use HTTP client library that allows us to easily send asynchronous HTTP requests to REST endpoints and perform CRUD operations. If you want to learn more about Axios, check out the guides on [Axios in Node.js](https://attacomsian.com/blog/http-requests-axios) and [Node.js HTTP client libraries](https://attacomsian.com/blog/http-requests-in-nodejs).
