HTTP requests using Axios

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

⭐️ 👀 2023 WEB DEVELOPMENT BOOTCAMP starting in days! Join the waiting list to reserve your spot in my 10-weeks cohort course and learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much much more! 👀 ⭐️

Introduction to 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.

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

A video tutorial

Check out this video where I create an Express server that offers a POST endpoint, and I make an Axios request to it, to post data:


Installation

Axios can be installed to be used in Node.js 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>

Remembering 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()

For the oldies, like in jQuery you would use $.get() and $.post() instead of $.ajax()

They offer a simpler syntax. For example:

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

Axios offers methods for all the HTTP verbs, which are less popular but still used:

  • axios.delete()
  • axios.put()
  • axios.patch()
  • axios.options()

and a method to get the HTTP headers of a request, discarding the body,axios.head().

GET requests

This Node.js example queries the Dog API to retrieve a list of all the dogs breeds, using axios.get(), and it counts them:

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'
})

One more thing! ⚠️ ✋

At the end of January I will organize the Web Development Bootcamp.

It's a 10-weeks long cohort online course where I will guide you to becoming a Web Developer.

It's not "just a course". It's a big event I organize once a year.

We'll start from zero, learn the fundamentals of Web Development, HTML CSS, JavaScript, Tailwind, Git, using the command line, VS Code, GitHub, Node.js, we'll then learn React, JSX, how to use PostgreSQL, Astro, Next.js, Prisma, deploying on Netlify/DigitalOcean/Fly/Vercel and much more! 

At the end of the first 10 weeks you'll know how to create web sites and web applications and I'll unlock you the 2nd phase of the Bootcamp: you will get access to a large number of projects exclusive to the Bootcamp graduates, so you can follow my instructions to build things like private areas with authentication, clones of popular sites like Twitter YouTube Reddit, create e-commerce sites, and much much more.

Because once you got the fundamentals, you only learn by working on real, exciting projects.

To find out more, visit bootcamp.dev