How to use Axios to make HTTP requests in JavaScript

published: 19 Sep 2022

2 min read

How to use Axios to make HTTP requests in JavaScript

Axios is an open-source library for making asynchronous HTTP requests to REST endpoints in the browser and Node.js. It is a promise-based 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:

# 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:

$ npm install axios -save

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

<script src='./node_modules/axios/dist/axios.min.js'></script>

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

<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:

index.html

<!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 - a simple, zero-configuration command-line HTTP server:

$ 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 for all our examples.

script.js

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, 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:

script.js

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:

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:

<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:

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:

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 an onclick event which handles the removal of the user when clicked:

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 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 and Node.js HTTP client libraries.

How to use Axios to make HTTP requests in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: nodejs, javascript, react, vuejs, programming
Check out what's on in the tag: nodejs, javascript, react, vuejs, programming, file