HTTP requests in Node using Axios

By

Learn how to make HTTP requests in Node.js with Axios, the promise-based library for GET and POST calls, adding query parameters and handling JSON for you.

~~~

Introduction

Axios is a very popular JavaScript library you can use to perform HTTP requests, that works in both Browser and Node.js platforms. The examples in this post use the 1.x line, which has been the current major since 2022.

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

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

For a broader Axios overview (browser + Node), see the main Axios guide.

Installation

Axios can be installed using npm:

npm install axios

or yarn:

yarn add axios

Then import it in your script:

import axios from 'axios'

This is the ES Modules syntax. Node runs it as long as your package.json has "type": "module" (or the file ends in .mjs). Without that, recent Node versions still detect the syntax and run the file, but print a warning. If your project uses CommonJS, const axios = require('axios') works the same.

In the browser you can also load Axios from a CDN with a script tag, see the official installation guide.

The Axios API

You can start an HTTP request from the axios object:

I use foo and bar as random names. Enter any kind of name to replace them.

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

but for convenience, you will generally use

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

and a method to get the HTTP headers of a request, discarding the body:

GET requests

One convenient way to use Axios is to use the modern (ES2017) async/await syntax.

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

import axios from '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:

import axios from 'axios'

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

const countBreeds = () => {
  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/?foo=bar.

With Axios you can perform this by using that URL:

axios.get('https://site.com/?foo=bar')

or you can use a params property in the options:

axios.get('https://site.com/', {
  params: {
    foo: 'bar'
  }
})

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/', {
  foo: 'bar'
})
Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: