Home Web Front-end JS Tutorial Axios and Fetch API? Choosing the Right HTTP Client

Axios and Fetch API? Choosing the Right HTTP Client

Dec 02, 2024 am 12:09 AM

TL;DR: Axios and Fetch API are popular HTTP clients. Axios offers more features and easier error handling, while Fetch API is lightweight and native to browsers. Choose Axios for complex projects and Fetch for simpler ones

Two of the most common methods for handling asynchronous HTTP requests are fetch() and Axios. Despite being a common operation, the type of request you choose to work with can have a considerable influence on the usability and overall efficiency of an app. So, it is wise to thoroughly examine them and weigh their pros and cons before choosing one.

This article will compare these two widely used tools comprehensively to help you make the best choice for your project.

What is Axios?

Axios and Fetch API? Choosing the Right HTTP Client is a promise-based, third-party HTTP client commonly seen in browser ( XMLHttpRequests ) and Node.js (HTTP) environments. It provides a convenient API capable of intercepting requests and responses, performing request cancellations, and automatically parsing response data to JSON format. Axios also supports client-side protection against XSRF (cross-site request forgery). You can install Axios with a package manager like npm or add it to your project via a CDN.

// NPM
npm install axios

// CDN
<script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
Copy after login
Copy after login
Copy after login

Advantages of Axios

  • Automatic request cancellation.
  • Built-in error handling, interceptors, and clean syntax.
  • Compatibility with a wide range of old and modern browsers.
  • Promise-based.

Disadvantages of Axios

  • External dependency.
  • Large bundle size and noticeable complexity.

What is fetch()?

Axios and Fetch API? Choosing the Right HTTP Client

The Fetch API is also promise-based but a native JavaScript API available in all modern browsers. It is also compatible with Node.js environments and replaced the legacy XMLHttpRequests with a simpler and more contemporary approach. The Fetch API provides the fetch() method to send requests and supports multiple request and response types such as JSON, Blob, and FormData.

Advantages of fetch()

  • Native browser support, so no external dependencies.
  • Lightweight and more straightforward API.
  • Promise-based.
  • fetch() is a low-level API. So, it provides more fine-grained control.

Disadvantages of fetch()

  • Limited built-in features for error handling and request time-out compared to Axios.
  • Verbose code for common tasks.

Differences between Axios and fetch()

Since you now understand what Axios and fetch() are, let’s compare and contrast some key features of these two with code examples.

Axios and Fetch API? Choosing the Right HTTP Client

Basic syntax

As far as syntax is concerned, Axios delivers a more compact and developer-friendly syntax than fetch().

Simple POST request with Axios:

// NPM
npm install axios

// CDN
<script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
Copy after login
Copy after login
Copy after login

Similar POST request with fetch():

axios.post('https://jsonplaceholder.typicode.com/todos', {
  userId: 11,
  id: 201,
  title: "Try Axios POST",
  completed: true
})
.then(response => {
  document.getElementById('output').innerHTML = `
    <h2>Post Created:</h2>
    <p>Title: ${response.data.title}</p>
    <p>Completed status: ${response.data.completed}</p>
  `;
})
.catch(error => {
  console.error('Error:', error);
  document.getElementById('output').innerHTML = '<p>Error creating post.</p>';
});
Copy after login
Copy after login

It is quite noticeable as even though fetch() is lightweight, it still requires more manual work to perform some common tasks. For instance, Axios comes with automatic JSON parsing and can directly access the data object of the response. In contrast, in fetch(), you have to parse the response to JSON format manually. Despite both presented approaches producing similar results, you have to explicitly handle the errors, serializations, and headers in fetch().

Error handling

Handling errors is something that developers encounter almost every day. Axios, for instance, handles any HTTP call with a status code outside the 2xx range as an error by default. It gives you an explanatory object that is useful in managing and debugging your errors.

fetch('https://jsonplaceholder.typicode.com/todos', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ // Manually converting the object to JSON
    userId: 11,
    id: 202,
    title: 'Try Fetch POST',
    completed: true
  })
})
.then(response => {
  if (!response.ok) { // Manual error handling for HTTP errors
    throw new Error('Error creating post');
  }
  return response.json(); // Manually parsing the response to JSON
});
Copy after login
Copy after login

fetch() does not automatically treat HTTP errors (status codes 4xx or 5xx) as errors. You have to perform conditional checks manually to identify the response status to capture the error. But you can have custom error-handling logic within your project to gather information and handle errors as Axios does.

axios.get('https://jsonplaceholder.typicode.com/invalid_endpoint')
 .then(response => {
  console.log(response.data);
 })
 .catch(error => {
  if (error.response) {
   // Server responded with a status outside of 2xx
   console.log('Error Status:', error.response.status);
   console.log('Error Data:', error.response.data);
 } else if (error.request) {
   console.log('Error Request:', error.request);
 } else {
   console.log('Error Message:', error.message);
 }});

Copy after login
Copy after login

Backward compatibility with browsers

If you need compatibility with legacy dependencies, such as an older browser like Internet Explorer (IE11) or older versions of most modern browsers, your go-to solution is Axios.

Axios and Fetch API? Choosing the Right HTTP Client

fetch() is native to modern browsers and functions seamlessly with them. However, it does not support some older browser versions. You can still use it with polyfills like whatwg-fetch to get it working in browsers that do not use fetch(). It is important to note that using polyfills might increase your bundle size and affect performance, though.

!(https://www.syncfusion.com/blogs/wp-content/uploads/2024/11/Fetch-compatibility.png)

HTTP interceptors

HTTP interceptors allow the intercepting of requests and responses and come in handy when:

  • Modifying requests (for example, when adding authentication to headers).
  • Transforming responses (preprocessing response data).
  • Handling errors globally (logging and redirecting when encountering a 401 unauthorized).

This powerful feature comes out of the box with Axios but is not natively supported by fetch().

Adding auth token to requests with Axios:

// NPM
npm install axios

// CDN
<script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
Copy after login
Copy after login
Copy after login

However, that does not mean fetch() cannot perform HTTP interception. You can use middleware to write a custom wrapper manually to mimic this behavior.

Adding auth token to requests with fetch() wrapper:

axios.post('https://jsonplaceholder.typicode.com/todos', {
  userId: 11,
  id: 201,
  title: "Try Axios POST",
  completed: true
})
.then(response => {
  document.getElementById('output').innerHTML = `
    <h2>Post Created:</h2>
    <p>Title: ${response.data.title}</p>
    <p>Completed status: ${response.data.completed}</p>
  `;
})
.catch(error => {
  console.error('Error:', error);
  document.getElementById('output').innerHTML = '<p>Error creating post.</p>';
});
Copy after login
Copy after login

Response time-out

Response time-out refers to the time a client will wait for the server to respond. If this time limit is reached, the request is counted as unsuccessful. Axios and fetch() support request time-outs, essential when dealing with unreliable or slow networks. Still, Axios takes the lead by providing a more straightforward approach to time-out management.

A request time-out with Axios:

fetch('https://jsonplaceholder.typicode.com/todos', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ // Manually converting the object to JSON
    userId: 11,
    id: 202,
    title: 'Try Fetch POST',
    completed: true
  })
})
.then(response => {
  if (!response.ok) { // Manual error handling for HTTP errors
    throw new Error('Error creating post');
  }
  return response.json(); // Manually parsing the response to JSON
});
Copy after login
Copy after login

A request time-out with fetch():

axios.get('https://jsonplaceholder.typicode.com/invalid_endpoint')
 .then(response => {
  console.log(response.data);
 })
 .catch(error => {
  if (error.response) {
   // Server responded with a status outside of 2xx
   console.log('Error Status:', error.response.status);
   console.log('Error Data:', error.response.data);
 } else if (error.request) {
   console.log('Error Request:', error.request);
 } else {
   console.log('Error Message:', error.message);
 }});

Copy after login
Copy after login

Axios handles the time-outs more simply and gracefully with cleaner code using its time-out option. But, fetch() needs manual timeout handling with AbortController(), which gives you more control over how and when the request is aborted.

GitHub reference

For more details, refer to the complete examples for Axios vs. Fetch on the GitHub repository.

Conclusion

As with many tools, both Axios and Fetch API come with strengths and weaknesses. If you require automatic parsing of JSON, integrated error handling, and interceptors to streamline complicated processes, go with Axios. Choose fetch() if you want a pure and simple interface that is best suited for modern browser environments and does not require an external library. In short, both work well, but they are suited to different levels of complexity and functionality requirements.

Related blogs

  • 5 Best Practices in Handling HTTP Errors in JavaScript
  • Top 5 Chrome Extensions for Handling HTTP Requests
  • How to Migrate ASP.NET HTTP Handlers and Modules to ASP.NET Core Middleware
  • Efficiently Handle CRUD Actions in Syncfusion ASP.NET MVC DataGrid with Fetch Request

The above is the detailed content of Axios and Fetch API? Choosing the Right HTTP Client. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles