Tutorial

How To Use Axios with JavaScript

Updated on March 17, 2021
How To Use Axios with JavaScript

Introduction

Axios is an open source library that allows you to make HTTP requests. It provides methods that include .get(), .post(), and .delete().

In this article, you will build a JavaScript application that uses Axios to perform GET, POST, and DELETE requests to a server for updates to a list of todo items.

Prerequisites

To complete this tutorial, you’ll need:

This tutorial was verified with Node v15.11.0, npm v7.6.1, axios v0.21.1, and parcel-bundler v1.12.5.

Step 1 — Setting Up the Project

In this section, you will create a new project directory, install package dependencies, and establish configuration files.

First, create a new project directory:

  1. mkdir axios-js-example

Then, change into the new project directory:

  1. cd axios-js-example

Next, initialize a new npm project:

  1. npm init -y

Then, install Axios:

  1. npm install axios@0.21.1

Note: Axios can also be added via a CDN:

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

Parcel is a tool to bundle and serve code. Install parcel-bundler as a dev dependency:

  1. npm install parcel-bundler@1.12.5 --save-dev

At this point, you will have a new project with axios and parcel-bundler.

Next, open package.json in your code editor. And modify the "scripts" to execute parcel for dev and build:

package.json
{
  // ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "parcel index.html",
    "build": "parcel build index.html"
  }
  // ...
}

Then, create a new app.js file. And add the following lines of code to avoid a “regeneratorRuntime is not defined” error when using await and async:

app.js
import 'regenerator-runtime/runtime';
import axios from 'axios';

Next, create a new index.html file. And add the following lines of code:

index.html
<!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;
      margin: 0;
      padding: 0;
    }
    li {
      margin-bottom: .5em;
      margin-top: .5em;
      padding: 1em;
      border: 1px solid white;
      transition-property: background-color, color;
      transition-duration: 500ms;
      transition-timing-function: ease-in-out;
    }
    li:hover {
      background-color: white;
      color: black;
    }
  </style>
</head>
<body>
  <div>
    <h1>Todos</h1>
    <ul>

    </ul>
  </div>
  <script src="app.js"></script>
</body>
</html>

This code will create an unordered list of todo items. Presently, this list will be empty, but it will be populated later.

Now, verify that your project is working up to this point. Open your terminal and run the following command:

  1. npm run dev

Then navigate to http://localhost:1234/ with your browser. You will observe a screen that says Todos.

Step 2 — Defining the GET Request

In this section, you will construct a function to utilize Axios to perform a GET HTTP request to the JSON Placeholder API.

Open app;js in your code editor. And add the following lines of code:

app.js
// ...

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

const getTodoItems = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/todos?_limit=5`);

    const todoItems = response.data;

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

    return todoItems;
  } catch (errors) {
    console.error(errors);
  }
};

Notice how axios.get is passed a path constructed out of the BASE_URL and a "todos" string. A _limit parameter is will restrict the response to 5 items.

This method will provide a response object back. This includes information about the response including things like headers, status, config, and most importantly, data.

Next, add code to create a todo element and append the todo elements to the list:

app.js
// ...

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

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

  return todoElement;
};

const updateTodoList = todoItems => {
  const todoList = document.querySelector('ul');

  if (Array.isArray(todoItems) && todoItems.length > 0) {
    todoItems.map(todoItem => {
      todoList.appendChild(createTodoElement(todoItem));
    });
  } else if (todoItems) {
    todoList.appendChild(createTodoElement(todoItems));
  }
};

const main = async () => {
  updateTodoList(await getTodoItems());
};

main();

Save your changes and view your application in the browser. You will observe a list with five items.

Step 3 — Defining the POST Request

In this section, you will construct a form and input to capture information for new todo items to add to the list. It will utilize Axios to perform a POST HTTP request.

Open index.html in your code editor. And add the following lines of code:

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- ... -->
  <style>
    /* ... */
    #new-todos form {
      margin-bottom: .5em;
      margin-top: .5em;
      padding: 1em;
      border: 1px solid white;
    }
  </style>
</head>
<body>
  <div id="new-todos">
    <h1>New Todo</h1>
    <form>
      <label>
        Name
        <input type="text" id="new-todos__title" />
      </label>
      <button type="submit">Add</button>
    </form>
  </div>
  <div>
    <h1>Todos</h1>
    <ul>

    </ul>
  </div>
  <script src="app.js"></script>
</body>
</html>

Next, open app.js in your code editor. And add the following lines of code:

app.js
// ...

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

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

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

  const todo = {
    userId: 1,
    title: title,
    completed: false
  };

  const submitTodoItem = await addTodoItem(todo);
  updateTodoList(submitTodoItem);
});

This code will take the value from the form and create a todo object.

Next, you will need to define the addTodoItem function inside of app.js:

app.js
// ...

export const addTodoItem = async todo => {
  try {
    const response = await axios.post(`${BASE_URL}/todos`, todo);
    const newTodoItem = response.data;

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

    return newTodoItem;
  } catch (errors) {
    console.error(errors);
  }
};

Notice how axios.post is passed a path and a payload containing the todo item.

Save your changes and view your application in the browser. You will observe a list with five items and a form. After using the form to add a new todo item, the list will update to display six items.

Step 4 — Defining the DELETE Request

In this section, you will create a click event on existing todo items to remove them from the list. It will utilize Axios to perform a DELETE HTTP request.

Next, you will need to define the deleteTodoItem function inside of app.js:

app.js
// ...

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

    return response.data;
  } catch (errors) {
    console.error(errors);
  }
};

Notice how axios.delete is passed a path that includes the id for the todo item:

Next, create a removeTodoElement function:

app.js
// ...

const removeTodoElement = async (event, element) => {
  event.target.parentElement.removeChild(element);
  const id = element.id;

  await deleteTodoItem(id);
};

This code will remove the element from the DOM and then call deleteTodoItem with the id.

Now, scroll back up to the createTodoElement function. You will add two new lines of code. When the list item element is created, you will also add an onclick event to the element to delete it. It will take the item id and pass it to removeTodoElement which in turn will call deleteTodoItem:

app.js
// ...

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

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

  todoElement.onclick = async event => await removeTodoElement(event, todoElement);

  return todoElement;
};

// ...

Save your changes and view your application in the browser. You will observe a list with five items and a form. After using the form to add a new todo item, the list will update to display six items. After clicking on one of the todo items, the list will display five items.

Conclusion

In this article, you built a JavaScript application that uses Axios to perform GET, POST, and DELETE requests to a server for updates to a list of todo items.

If you’d like to learn more about Axios, check out the guides on React with Axios and Vue with Axios.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thank you so much.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel