DEV Community

Cover image for Axios vs Fetch
Caio
Caio

Posted on

Axios vs Fetch

Both Axios and Fetch are popular tools for making HTTP requests in JavaScript, but they have some key differences. Here’s a breakdown:

Axios

Built-in Features: Axios comes with many built-in features like automatic JSON transformation, request and response interceptors, and cancellation of requests.
Browser Compatibility: It supports older browsers, including Internet Explorer.
Error Handling: Axios automatically rejects promises for HTTP error statuses (like 404 or 500), making error handling simpler.
Request/Response Interceptors: You can easily modify requests or responses globally.
Cancel Requests: Axios provides an easy way to cancel requests.

Fetch

Native API: Fetch is a native web API, meaning you don’t need to install any additional libraries.
Promise-Based: It uses Promises, but you need to manually check the response status for errors.
Stream Handling: Fetch supports streaming, which can be useful for handling large responses.
More Control: You have more control over requests, but it requires more boilerplate code for features like setting defaults or intercepting requests.
No Built-in Support for JSON: You need to call .json() on the response object to parse JSON data.

Use Cases

Use Axios if you need a rich feature set out of the box, especially for complex applications.
Use Fetch for simpler use cases or when you want to avoid external dependencies.
Example Usage

Axios:

axios.get('/api/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode
// axios
const options = {
  url: 'http://localhost/test.htm',
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  data: {
    a: 10,
    b: 20
  }
};
axios(options)
  .then(response => {
    console.log(response.status);
  });
Enter fullscreen mode Exit fullscreen mode

Now compare this code to the fetch() version, which produces the same result:

fetch('/api/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode
// fetch()

const url = "https://jsonplaceholder.typicode.com/todos";
const options = {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json;charset=UTF-8",
  },
  body: JSON.stringify({
    a: 10,
    b: 20,
  }),
};
fetch(url, options)
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  });

Enter fullscreen mode Exit fullscreen mode

Notice that:

To send data, fetch() uses the body property for a post request to send data to the endpoint, while Axios uses the data property
The data in fetch() is transformed to a string using the JSON.stringify method
Axios automatically transforms the data returned from the server, but with fetch() you have to call the response.json method to parse the data to a JavaScript object
With Axios, the data response provided by the server can be accessed within the data object, while for the fetch() method, the final data can be named any variable

Conclusion

Both have their strengths, and the choice often comes down to your specific needs and preferences. If you're building a larger application with many API interactions, Axios might save you some hassle, while Fetch is great for straightforward tasks.

Axios offers a user-friendly API that simplifies most HTTP communication tasks. However, if you prefer using native browser features, you can definitely implement similar functionalities yourself with the Fetch API.

As we've explored, it’s entirely feasible to replicate the essential features of Axios using the fetch() method available in web browsers. The decision to include a client HTTP library ultimately depends on your comfort level with native APIs and your specific project requirements.

For more information: https://blog.logrocket.com/axios-vs-fetch-best-http-requests/

Top comments (6)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

I don't understand the fixation of people with axios. It should just be a legacy package. This is no longer needed. Just go with a customized function that uses fetch. The customized function can replace all interception needs. Far simpler and no package dependencies.

Collapse
 
cookiemonsterdev profile image
Mykhailo Toporkov 🇺🇦 • Edited

Axios is good when you need to support old browsers, since it uses XHR under the hood. But from the other hand it slower than fetch API, I would recommend to use ky, it has same features like req, res interception and automatically rejection HTTP errors by status. Ky is using fetch as base so it faster.

Collapse
 
abdulmuminyqn profile image
Abdulmumin yaqeen

I think fetch satisfies most needs, but axios is good to have.

nice read!

Collapse
 
martinbaun profile image
Martin Baun

I use Axios for interceptors feature which afaik fetch doesn’t have.
Sure I could build my own, but then I’d have to build my own

Collapse
 
tomasdevs profile image
Tomas Stveracek

Nice read. I wrote a similar article for those interested. Link here.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.