Using Axios: A Deep Dive

Axios is a promise-based HTTP client that works in both browser and Node.js environments. It’s widely used in modern JavaScript applications due to its simplicity and powerful features.

Why Use Axios?

Axios offers several benefits over the native fetch API:

  • Simpler and more concise syntax
  • Automatic JSON data transformation
  • Request and response interceptors
  • Global configuration for headers, base URL, etc.
  • Built-in support for request cancellation
  • Works on both client and server (Node.js)
  • Handles timeouts and error handling gracefully

Installation

npm install axios
# or
yarn add axios

Basic Usage

GET Request

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error fetching posts:', error));

POST Request

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

Axios Instance for Custom Configuration

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
});

api.get('/endpoint')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Advanced Features of Axios

Interceptors

axios.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer myToken';
  return config;
});

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      console.warn('Unauthorized, redirect to login');
    }
    return Promise.reject(error);
  }
);

Canceling Requests

const controller = new AbortController();

axios.get('/api/data', { signal: controller.signal })
  .then(response => console.log(response))
  .catch(error => console.error('Request canceled:', error));

// Cancel the request manually
controller.abort();

Global Defaults

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 10000;

Axios Error Handling

Axios categorizes errors as server errors, network errors, or request setup errors:

axios.get('/api/data')
  .catch(error => {
    if (error.response) {
      // Server responded with a status code out of 2xx
      console.error('Server Error:', error.response.status);
    } else if (error.request) {
      // No response received
      console.error('Network Error:', error.request);
    } else {
      // Something else happened
      console.error('Axios Error:', error.message);
    }
  });

Summary

FeatureAxiosFetch API
JSON HandlingAutomaticManual (.json())
InterceptorsYesNo
Cancel RequestsYesPartial support
Timeout SupportYesNo
Node.js SupportYesNo
Global ConfigYesNo

Axios is a robust, flexible HTTP client that simplifies API integration in both frontend and backend environments. Mastering it helps streamline data fetching, improve error handling, and enhance overall app performance.

Share this content:

Hi, my name is Toni Naumoski, and I’m a Senior Frontend Developer with a passion for blending code and design. With years of experience as a Frontend Developer, Web Designer, and Creative Technologist, I specialize in crafting unique, responsive, and detail-oriented websites and web applications that stand out. I bring deep expertise in HTML, CSS, and JavaScript—working fluently with modern frameworks like React, Angular, and Vue, as well as animation libraries like GSAP. My creative side thrives in Photoshop and Figma, and I enjoy extending functionality using tools like Express.js and ChatGPT. My work is guided by high integrity, strong communication, a positive attitude, and a commitment to being a reliable collaborator. I take pride in delivering high-quality digital experiences that are both technically solid and visually compelling.

Post Comment