How to use Axios with JavaScript

Paul Halliday

Axios is an open source library that allows us to easily make HTTP requests. It’s effectively just fetch with extra superpowers!

Let’s see this in action by creating a new HTML5 project:

# Create directory with a name of your choosing
$ mkdir axios-js && cd axios-js

# Create files
$ touch index.html app.js

# Initialise a new npm project
$ npm init -y

# Install Axios
$ npm i axios -S

$ npm i parcel-bundler -D

# Open this up in your editor
$ code .
Learn JavaScript basics for free

NOTE: Axios can also be added via a CDN like so: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

As you may be able to see from our npm install calls, we’ll be using Parcel to bundle and serve our code. We can add an npm script for this by heading over to package.json:

{
  "scripts": {
    "dev": "parcel index.html",
    "build": "parcel build index.html"
  }
}

As we’ll be using async and await inside of our project, we’ll install Babel and the @babel/polyfill package:

$ npm i @babel/core @babel/polyfill

Start your project by running npm run dev in your terminal and navigate to http://localhost:1234/. We can then update index.html with our app.js and some minor semantics:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vanilla Axios</title>

  <style>
    body {
      background-color: #673AB7;
      color: white;
    }
    ul {
      list-style: none;
    }
  </style>
</head>
<body>

  <div>
    <h1>Todos</h1>
    <ul>
      
    </ul>
  </div>
  <script src="app.js"></script>

</body>
</html>

GET

Inside of app.js, let’s make a function that allows us to GET Todos from an API. We’ll be using the JSON Placeholder API for our example.

import axios from 'axios';

const BASE_URL = 'https://jsonplaceholder.typicode.com';

const getTodos = async () => {
  try {
    const res = await axios.get(`${BASE_URL}/todos`);

    const todos = res.data;

    console.log(`GET: Here's the list of todos`, todos);

    return todos;
  } catch (e) {
    console.error(e);
  }
};

Axios almost makes it almost too simple to get data from a server, which is great news for us. Simply pass axios.get the BASE_URL and you’ll get a response object back.

This includes information about our response including things like headers, status, config and most importantly, data.

We can extend our application to now add this data to the DOM:

const createLi = item => {
  const li = document.createElement('li');

  li.appendChild(document.createTextNode(item.title));

  return li;
};

const addTodosToDOM = todos => {
  const ul = document.querySelector('ul');

  if (Array.isArray(todos) && todos.length > 0) {
    todos.map(todo => {
      ul.appendChild(createLi(todo));
    });
  } else if (todos) {
    ul.appendChild(createLi(todos));
  }
};

const main = async () => {
  addTodosToDOM(await getTodos());
};

main();

POST

We can add Todos to our API by capturing some information about it inside of a form and input:

<div id="new-todos">
  <h1>New Todo</h1>
  <form>
    <label>
      Name
      <input type="text" id="new-todos__name" />
    </label>
    <label>
      userId
      <input type="text"  id="new-todos__userId" />
    </label>
    <button type="submit">Add</button>
  </form>
</div>

We can then add the Todo by listening for the submit event:

const form = document.querySelector('form');

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

  const title = document.querySelector('#new-todos__title').value;
  const userId = document.querySelector('#new-todos__userId').value;

  const todo = {
    title,
    userId
  };

  const addedTodo = await addTodo(todo);
  addTodosToDOM(addedTodo);
});

We’ll need to create the addTodo function inside of app.js. The major difference between this and the get example is that we’re adding the todo payload.

export const addTodo = async todo => {
  try {
    const res = await axios.post(`${BASE_URL}/todos`, todo);
    const addedTodo = res.data;

    console.log(`Added a new Todo!`, addedTodo);

    return addedTodo;
  } catch (e) {
    console.error(e);
  }
};

DELETE

What good is a Todo list if we can’t delete items? Let’s add that functionality. We can create a deleteTodo function inside of app.js:

export const deleteTodo = async id => {
  try {
    const res = await axios.delete(`${BASE_URL}/todos/${id}`);
    console.log(`Deleted Todo ID: `, id);

    return res.data;
  } catch (e) {
    console.error(e);
  }
};

Within our createLi function we can attach an onclick event which handles the removal of our Todo when it’s clicked. The DELETE method requires an id to be passed as a parameter, so we can also add an id to each element at this stage.

const createLi = item => {
  const li = document.createElement('li');

  li.id = item.id;
  li.appendChild(document.createTextNode(item.title));

  // Remove LI on click
  li.onclick = async e => await removeTodo(e, li);

  return li;
};

Inside of removeLi we can remove the Todo from the DOM and then call deleteTodo with the ID:

const removeTodo = async (e, li) => {
  e.target.parentElement.removeChild(li);
  const id = li.id;

  await deleteTodo(id);
};

Summary

This article looked at a few of the key ways to interact with an API using Axios using a very simple Todo application. If you’d like to learn more about Axios, check out the guides on React + Axios and Vue + Axios.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#