Axios CheatSheet



This Axios cheatsheet is based on Axios and uses this widely popular HTTP client for making API requests in JavaScript. It describes installing Axios, and performing CRUD operations and also has advanced features such as request interceptors, authorization headers, and retry logic. You will also get to know how to set up global configurations, manage errors, transform requests and responses, and make simultaneous requests as well. For more detail on best practices when it comes to secure, dynamic, and modular API integration, check the document itself.

Table of Contents

Introduction

Axios. js is a light weight JavaScript library for making HTTP requests from the browser or Node. js. It makes API interactions quick by offering an easy-to-use promise-based syntax for making GET, POST, PUT, DELETE, and other HTTP methods. Axios reviews often commend its simple handling of JSON data, easy to manage request and response interceptors, and efficient error handling.

Installing and Basics

Install Axios using npm

npm install axios

Basic

import axios from 'axios';
const instance = axios.create({
   baseURL: 'https://api.example.com',
   timeout: 1000,
   headers: { 'Authorization': 'Bearer token' }
});

CRUD Operations Using Axios

GET Request

Fetches data from an API endpoint

axios.get('https://reqres.in/api/users?delay=2')
.then(response => {
   console.log(response.data);
})
.catch(error => {
   console.log("This is error: " + error.response);
})
.finally(() => {
   // always executed
});

POST Request

Sends data to an API endpoint

axios.post('https://reqres.in/api/users', {
   "name": "aman",
   "job": "it"
})
.then(response => {
   console.log(response.data);
})
.catch(error => {
   console.log(error.response);
})
.finally(() => {
   // always executed
});

PUT Request

Updates existing data on an API endpoint.

axios.put('https://reqres.in/api/users/2', {
   "name": "Raju",
   "job": "Dev Ops"
})
.then(response => {
   console.log(response.data);
})
.catch(error => {
   console.log(error.response);
})
.finally(() => {
   // always executed
});

DELETE Request

Deletes data from an API endpoint.

axios.delete('https://reqres.in/api/users?page=2')
.then(response => {
   console.log(response.data);
})
.catch(error => {
   console.log(error.response);
})
.finally(() => {
   // always executed
});

Requests with Authorization Headers

Sends requests with an authorization token.

axios.post('https://reqres.in/api/users', {
   "data": "somedata"
}, {
   headers: { 'Authorization': 'Token' }
})
.then(response => {
   console.log(response.data);
})
.catch(error => {
   console.log(error.response);
})
.finally(() => {
   // always executed
});

Advanced Axios Features

Base URL Configuration

Set up a base URL for cleaner code.

axios.defaults.baseURL = 'https://api.example.com';

Handling Responses and Errors

Handle successful and error responses.

axios.get('/endpoint')
.then(response => {
   console.log(response.data);
})
.catch(error => {
   console.error("Error: ", error.message);
});

Request and Response Interceptors

Modify requests and responses globally.

// Add a request 
axios.interceptors.request.use(config => {
   config.headers['Authorization'] = 'Bearer token';
   return config;
}, error => Promise.reject(error));

// Add a response 
axios.interceptors.response.use(response => response, error => {
   console.error("Global error: ", error.response);
   return Promise.reject(error);
});

Custom Axios Instances

Create reusable instances with specific configurations.

const apiClient = axios.create({
   baseURL: 'https://api.example.com',
   timeout: 2000
});

Retry Logic

Implement automatic retries using axios-retry.

import axiosRetry from 'axios-retry';

axiosRetry(axios, { retries: 3 });

Progress Tracking

Monitor file upload/download progress.

axios.post('/upload', formData, {
   onUploadProgress: progressEvent => {
      console.log(`Uploaded: ${(progressEvent.loaded / progressEvent.total) * 100}%`);
   }
});

Request Cancellation

Cancel ongoing requests using CancelToken or AbortController.

const controller = new AbortController();

axios.get('/endpoint', { signal: controller.signal })
.catch(error => {
   if (error.name === 'CanceledError') {
      console.log('Request canceled');
   }
});

// Cancel the request
controller.abort();

Timeouts

Set timeouts for requests.

axios.get('/endpoint', { timeout: 5000 })
.catch(error => {
   if (error.code === 'ECONNABORTED') {
      console.error('Request timed out');
   }
});

Query Parameters

Pass query strings in requests.

axios.get('/endpoint', {
   params: { id: 123, sort: 'desc' }
});

Headers and Authorization

Authorization Header

axios.get('/user', {
   headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
})
   .then(response => console.log(response.data))
   .catch(error => console.error(error));

Custom Headers

axios.post('/submit', data, {
   headers: { 'Custom-Header': 'value' }
})
   .then(response => console.log(response.data))
   .catch(error => console.error(error));

Handling Global Configuration

Set a Global Base URL −

axios.defaults.baseURL = 'https://api.example.com';

Set Global Headers

axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';

Transforming Requests and Responses

Transforming Requests

axios.defaults.transformRequest = [(data) => {
   // Modify request data
   return JSON.stringify(data);
}];

Transforming Responses

axios.defaults.transformResponse = [(data) => {
   // Modify response data
   return JSON.parse(data);
}];

Handling Multiple Requests Simultaneously

axios.all([
   axios.get('/user'),
   axios.get('/posts')
])
.then(axios.spread((userResponse, postsResponse) => {
   console.log(userResponse.data);
   console.log(postsResponse.data);
}))
.catch(error => console.error(error));

Handling Errors Globally

axios.interceptors.response.use(
   response => response,
   error => {
      if (error.response.status === 401) {
         console.log("Unauthorized: Redirecting to login...");
         // Redirect or handle refresh token logic
      } else if (error.response.status === 500) {
         console.log("Server error, please try again later.");
      }
      return Promise.reject(error);
   }
);
Advertisements