Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Comparing Fetch API and Axios for HTTP Requests

Tech Sep 2 3

Handling Cookies

When making same-origin requests, both fetch and axios automatically include cookies. For cross-origin scenarios, however, different configurations are required:

  • Fetch: You must explicitly set the credentials option to 'include' in the configuration object.
  • Axios: You must set withCredentials: true within the request configuration.

Using the Fetch API

fetch is built into modern browsers, reqiuring no additional dependencies. It returns a Promise and operates at a lower level, meaning developers must manually parse response bodies using methods like .json(), .text(), or .blob().

To manage request cancellation, utilize the AbortController interface:

const controller = new AbortController();

fetch('/api/data', {
  method: 'GET',
  signal: controller.signal
})
  .then(response => {
    if (!response.ok) throw new Error(`Status: ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Request aborted');
    } else {
      console.error('Fetch failed:', err);
    }
  });

// Trigger cancellation
controller.abort();

Using Axios

axios is a feature-rich, promise-based library that simplifies HTTP interactions at the cost of increasing bundle size. Key advantages include:

Concurrent Requests

Axios provides built-in utilities for executing multiple requests simultaneously:

import axios from 'axios';

async function fetchDashboardData() {
  const [profile, settings] = await axios.all([
    axios.get('/api/profile'),
    axios.get('/api/settings')
  ]);
  console.log('Profile:', profile.data);
  console.log('Settings:', settings.data);
}

Automatic Serialization

Unlike fetch, which requires an explicit parsing step, axios automatically transforms JSON responses into objects.

// Axios handles JSON parsing automatically
axios.get('/api/config').then(res => console.log(res.data));

Request and Response Interceptors

Interceptors allow you to transform requetss or handle errors globally before they are passed to the application logic.

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

axios.interceptors.response.use(res => res, err => {
  if (err.response.status === 401) {
    // Handle session expiry
  }
  return Promise.reject(err);
});

Request Cancellation

Axios supports the AbortController standard in newer versions, providing a consistent way to stop ongoing operations:

const controller = new AbortController();

axios.get('/api/long-task', {
  signal: controller.signal
}).catch(err => {
  if (axios.isCancel(err)) {
    console.log('Request canceled by user');
  }
});

controller.abort();

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.