Other JavaScript Libraries: Axios

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Axios

Axios is a very popular JavaScript library you can use to perform HTTP requests, that works in both Browser and Node.js platforms.

It supports all modern browsers, including support for IE8 and higher.

It is promise-based, and this lets us write async/await code to perform XHR requests very easily.

Why use Axios over Fetch?

Using Axios has quite a few advantages over the native Fetch API:

  • supports older browsers (Fetch needs a polyfill)
  • has a way to abort a request
  • has a way to set a response timeout
  • has built-in CSRF protection
  • supports upload progress
  • performs automatic JSON data transformation
  • works in Node.js

Installation

Axios can be installed using npm:

npm install axios

In the browser, you can include it in your page using unpkg.com:

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

Remember that API calls must enable CORS to be accessed inside the browser, otherwise the request will fail.

The Axios API

You can start an HTTP request from the axios object:

axios({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get'
})

This returns a promise. You can use async/await to resolve that promise to the response object:

;(async () => {
  const response = await axios({
    url: 'https://dog.ceo/api/breeds/list/all',
    method: 'get'
  })

  console.log(response)
})()

For convenience, you will generally use the methods:

  • axios.get()
  • axios.post()

They offer a simpler syntax:

;(async () => {
  const response = await axios.get('https://dog.ceo/api/breeds/list/all')
  console.log(response)
})()

Axios offers methods for all the HTTP verbs:

  • axios.delete()
  • axios.put()
  • axios.patch()
  • axios.options()
  • axios.head() - get HTTP headers, discarding the body

GET requests

This Node.js example queries the Dog API to retrieve a list of all the dogs breeds:

const axios = require('axios')

const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = await getBreeds()

  if (breeds.data.message) {
    console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
  }
}

countBreeds()

If you don’t want to use async/await you can use the Promises syntax:

const axios = require('axios')

const getBreeds = () => {
  try {
    return axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = getBreeds()
    .then(response => {
      if (response.data.message) {
        console.log(
          `Got ${Object.entries(response.data.message).length} breeds`
        )
      }
    })
    .catch(error => {
      console.log(error)
    })
}

countBreeds()

Add parameters to GET requests

A GET response can contain parameters in the URL, like this: https://site.com/?name=Flavio.

With Axios you can perform this by using that URL:

axios.get('https://site.com/?name=Flavio')

or you can use a params property in the options:

axios.get('https://site.com/', {
  params: {
    name: 'Flavio'
  }
})

POST Requests

Performing a POST request is just like doing a GET request, but instead of axios.get, you use axios.post:

axios.post('https://site.com/')

An object containing the POST parameters is the second argument:

axios.post('https://site.com/', {
  name: 'Flavio'
})

Forcing credentials on every request

When working with APIs that set JWT tokens in cookies, you need to set withCredentials: true:

import axios from 'axios'

axios.post(API_SERVER + '/login', { email, password }, { withCredentials: true })

For many requests, you can create a reusable Axios instance:

import axios from 'axios'

const instance = axios.create({
  withCredentials: true,
  baseURL: API_SERVER
})

instance.get('todos')

With React and axios-hooks:

import axios from 'axios'
import useAxios, { configure } from 'axios-hooks'

const instance = axios.create({
  withCredentials: true,
  baseURL: API_SERVER,
})

configure({ instance })

const [{ data, loading, error }, refetch] = useAxios('todos')

Sending the authorization header

To set headers in an Axios POST request, pass a third object to the axios.post() call:

const token = '..your token..'

axios.post(url, {
  //...data
}, {
  headers: {
    'Authorization': `Basic ${token}` 
  }
})

For GET requests:

axios.get('https://api.github.com/user', {
  headers: {
    'Authorization': `token ${access_token}`
  }
})
.then((res) => {
  console.log(res.data)
})
.catch((error) => {
  console.error(error)
})

For basic authentication:

const username = ''
const password = ''

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

const url = 'https://...'
const data = {
  ...
}

axios.post(url, data, {
  headers: {
    'Authorization': `Basic ${token}`
  },
})

Sending URL-encoded data

When an API only accepts urlencoded format, use the qs module:

npm install qs

Then:

import qs from 'qs'
import axios from 'axios'

axios({
  method: 'post',
  url: 'https://my-api.com',
  data: qs.stringify({
    item1: 'value1',
    item2: 'value2'
  }),
  headers: {
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
  }
})

Lessons in this unit:

0: Introduction
1: jQuery
2: ▶︎ Axios
3: Moment.js
4: SWR
5: XState
6: PeerJS