Axios

Language: JavaScript

Web

Axios was created to provide a simpler and more consistent API for making HTTP requests in JavaScript compared to the built-in `fetch` API. It supports request and response interception, automatic JSON transformation, and is widely adopted in both front-end and back-end JavaScript projects.

Axios is a promise-based HTTP client for JavaScript that works in both the browser and Node.js. It simplifies making HTTP requests, handling responses, and managing errors.

Installation

npm: npm install axios
yarn: yarn add axios

Usage

Axios allows you to perform HTTP requests using methods such as GET, POST, PUT, DELETE, and more. It returns promises that resolve with response objects containing data, status, headers, and config. Axios also supports request cancellation, interceptors, and timeout configuration.

GET request

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Performs a GET request to the given URL and logs the response data.

POST request with JSON payload

import axios from 'axios';

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

Sends a POST request with a JSON payload and logs the returned data.

Setting custom headers

axios.get('https://jsonplaceholder.typicode.com/posts', {
    headers: { 'Authorization': 'Bearer my-token' }
})
.then(response => console.log(response.data));

Adds custom headers to a request, useful for authentication or custom API requirements.

Using interceptors

axios.interceptors.request.use(config => {
    console.log('Request made with config:', config);
    return config;
});
axios.interceptors.response.use(response => {
    console.log('Response received:', response);
    return response;
});

Intercepts requests and responses globally for logging, modifying headers, or handling errors.

Canceling requests

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', { cancelToken: source.token });
source.cancel('Request canceled by user.');

Demonstrates canceling a request using Axios CancelToken.

Concurrent requests

axios.all([
  axios.get('/users'),
  axios.get('/posts')
]).then(axios.spread((usersRes, postsRes) => {
  console.log(usersRes.data, postsRes.data);
}));

Performs multiple HTTP requests concurrently and handles the responses together.

Error Handling

Network Error: Check your internet connection or the API endpoint availability.
Timeout Error: Set a reasonable timeout using `axios({ timeout: 5000 })` and handle cases where the request takes too long.
HTTP error (4xx, 5xx): Use `error.response` to inspect status codes and messages, and handle specific status codes appropriately.

Best Practices

Use interceptors for handling authentication, logging, or error processing.

Always catch errors and handle them gracefully.

Use environment variables for base URLs and API tokens.

Leverage request cancellation to avoid race conditions or unnecessary network calls.

Use async/await syntax for cleaner asynchronous code.