How to use Axios with JavaScript
Table of contents
How to use Axios with JavaScript
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:
shell
# 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# install Babel to use async/await$ npm i @babel/core @babel/polyfill$ npm i parcel-bundler -D# Open this up in your editor$ code .
note
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
:
json
{"scripts": {"dev": "parcel index.html","build": "parcel build index.html"}}
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:
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;}</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.
js
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);}};