Why Axios is Preferred Over Fetch

The Fetch API provides a modern and extensible way to send HTTP requests in JavaScript. It is included in most recent browsers, allowing developers to retrieve resources asynchronously over the network. Fetch is generally regarded for its simplicity, adaptability, and ability to handle a wide range of requests. Unlike older techniques like XMLHttpRequest, Fetch has a more robust and versatile feature set, including promises, which enable more straightforward asynchronous code.

Axios on the other hand is a promise-based HTTP client for JavaScript that runs in both the browser and Node.js. It is a popular alternative to the Fetch API, offering a higher-level abstraction with additional functionality to help manage HTTP requests. Axios is frequently used for its simple syntax, automated JSON data processing, and more robust error handling capabilities.

Key Advantages of Axios Over Fetch

In this section, we’ll be focusing on the key advantages Axios has over Fetch. Let’s get straight to it:

  • Ease of Use and Simplicity:

One of the main reasons developers choose Axios to Fetch is its ease of usage and simplicity. Axios abstracts away many of the complexity of HTTP requests, allowing developers to write cleaner, more concise code. For example, while Fetch requires chaining multiple .then() methods to handle responses, Axios exposes the result data directly, making it easy to work with.

For example:

// Fetch Example
fetch("https://api.example.com/data")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

// Axios Example
axios
  .get("https://api.example.com/data")
  .then((response) => console.log(response.data))
  .catch((error) => console.error("Error:", error));

From the code above, you can see that axios makes the process simple minimizing boilerplate code and making it easier to respond directly.

  • Error Handling:

Error management in Fetch can be tedious since it necessitates manual checks for HTTP response status codes. In contrast, Axios immediately throws an exception for any HTTP response status codes that lie outside the range of 2xx, making issues easy to detect and address.

Example:

// Fetch Example
fetch("https://api.example.com/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("Fetch Error:", error));

// Axios Example
axios
  .get("https://api.example.com/data")
  .then((response) => console.log(response.data))
  .catch((error) => console.error("Axios Error:", error));

With Axios, there is no need to manually check the status code because it is already handled, providing for easier error handling.

  • Interceptors for Requests and Responses:

Axios includes a powerful feature called interceptors, which allow you to intercept and change requests or answers before they are handled by.then() or.catch(). This is very beneficial for activities such as providing authentication tokens to requests, logging, and treating responses consistently throughout the application.

// Adding a request interceptor
axios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Adding a response interceptor
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      // Handle unauthorized access
    }
    return Promise.reject(error);
  }
);

Interceptors provide a centralized approach to managing request and response transformations, which improves code maintainability and reduces duplication.

  • Request and Response Transformation:

Axios automatically transforms JSON data when sending and receiving requests, eliminating the need to manually parse JSON in most circumstances. This functionality can save time and lessen the likelihood of errors when interacting with APIs that rely heavily on JSON.

// Axios handles JSON transformation automatically
axios
  .post("https://api.example.com/data", {
    name: "John Doe",
    age: 30,
  })
  .then((response) => console.log(response.data))
  .catch((error) => console.error("Error:", error));

In this example, Axios automatically turns the JavaScript object into a JSON string for the request and parses the response data as JSON.

  • Default Settings and Global Configuration:

One of Axios' notable features is the ability to configure global settings, such as default headers and base URLs, that apply to all requests. This is especially beneficial for apps that connect with the same API from several components or files.

// Setting default configurations
axios.defaults.baseURL = "https://api.example.com";
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
axios.defaults.headers.post["Content-Type"] = "application/json";

// Now you can make requests without repeating the base URL or headers
axios
  .get("/user/12345")
  .then((response) => console.log(response.data))
  .catch((error) => console.error("Error:", error));

With global configurations, Axios streamlines the setup process, eliminating repetition and the possibility of errors in your code base.

  • Cancellation of Requests: Handling request cancellations in Axios:

Axios' CancelToken makes it straightforward to end ongoing requests. This capability is very handy when dealing with situations like as auto-complete inputs, where you may want to cancel prior requests that are no longer required as the user continues to type.

const source = axios.CancelToken.source();

axios
  .get("/user/12345", {
    cancelToken: source.token,
  })
  .then((response) => console.log(response.data))
  .catch((thrown) => {
    if (axios.isCancel(thrown)) {
      console.log("Request canceled", thrown.message);
    } else {
      console.error("Error:", thrown);
    }
  });

// Cancel the request
source.cancel("Operation canceled by the user.");

This functionality optimizes network use and improves the user experience by minimizing needless requests.

  • Browser Compatibility:

Fetch is supported by all modern browsers, however it may have difficulties in older browsers, particularly Internet Explorer. Axios, on the other hand, offers more compatibility, including support for Internet Explorer 11 and previous versions. This makes Axios a safer choice for projects that require support for a wider range of browsers.

Conclusion

Making HTTP requests is an important activity in web development, and selecting the correct tool for the job can have a significant impact on your code's performance and maintainability. While the Fetch API provides a natural and versatile mechanism to handle HTTP requests in modern browsers, it necessitates more manual intervention, particularly for error checks, JSON processing, and complex setups. Axios, on the other hand, distinguishes itself with its simplicity, ease of usage, and powerful capabilities such as interceptors, automatic data translation, and global configuration settings. These capabilities not only speed up the development process, but they also reduce the amount of boilerplate code, making complicated applications easier to manage.