Making network requests with Axios

Published on Sep 12, 2022

Axios is a simple promise based HTTP client for the browser and node.js. Axios provides a simple to use library in a small package with a very extensible interface. Read more here.

Installation

Install Axios with npm:

npm install axios

Or with yarn:

yarn add axios

Usage

Import Axios in your component:

import axios from 'axios'

GET Requests

Make a request for a user with a given ID:

axios.get('/projects/42')

To make a request using GET params:

axios.get('/projects', {
  params: {
    id: 42
  }
})

Async GET requests

Make a request using an async function:

async function getProject() {
  try {
    const response = await axios.get('/projects/42');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

POST Requests

Send some data:

axios.post('/projects', {
  title: 'Write a blog post',
  abstract: 'Write a blog post about Axios'
})

Handling success & errors

To handle success response or errors:

axios.get('/projects/42')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

To access response headers:

axios.get('/projects/42')
  .then(function (response) {
    // handle success
    console.log(response.headers);
  });

To access response status:

axios.get('/projects/42')
  .then(function (response) {
    // handle success
    console.log(response.status);
  });

To access response status text:

axios.get('/projects/42')
  .then(function (response) {
    // handle success
    console.log(response.statusText);
  });

To access response data:

axios.get('/projects/42')
  .then(function (response) {
    // handle success
    console.log(response.data);
  });

Canceling requests

Cancel a request:

var CancelToken = axios.CancelToken;

var source = CancelToken.source();

axios.get('/user/42', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

Concurrent requests

Make multiple concurrent requests:

function getProjects() {
  return axios.get('/projects');
}

function getUsers() {
  return axios.get('/users');
}

axios.all([getProjects(), getUsers()])
  .then(axios.spread(function (projects, users) {
    // Both requests are now complete
  }));

Best Practices

Here are some best practices to follow when using Axios.

Specialised Service

Rather than using Axios call all over the components, create a speciased "service", inside a src/services folder. For example, if you want to make a request to get all the projects, create a ProjectService.js file and export a function that will make the request:

src/services/ProjectService.js

import axios from 'axios'

const apiClient = axios.create({
  baseURL: 'https://my-api.com',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

export default {
  getAll() {
    return apiClient.get('/projects')
  },
  get(id) {
    return apiClient.get('/projects/' + id)
  }
}

Then import the service in your component and call the function:

import ProjectService from '@/services/ProjectService'

export default {
  data() {
    return {
      projects: []
    }
  },
  mounted() {
    ProjectService.getAll()
      .then(response => {
        this.projects = response.data
      })
  }
}

Axios configuration file

create a src/services/axios.js file to configure Axios and export it.