Are you trying to choose between the Axios Library and the Fetch API for your next project? Let us help you make the decision.
Should I use the fetch API? This is a question I always wrestled with when beginning a new front-end project. If not, should I use Axios? Are you also in the same scenario and looking for a better guide to decide where to stick? To help you choose the right tools, I’ll explain the difference between Axios Library and Fetch API- HTTP Call Comparison within this blog post.
What is Axios Library?
Axios is an NPM library for retrieving data from servers, similar to Fetch API. Axios are used on both the server’s and the browser’s side. This occurs as a result of the fact that each side uses a different approach to obtain the data. It uses XMLHttpRequest on the browser side and the http module on the service side. Below is the sample code of this Axios Library API.
axios.get('/user?ID=12345').then(function (response) {
console.log(response.data);
});
What is Fetch API?
The built-in browser's Fetch API is used to retrieve data from services. This API is essentially a simplified version of XMLHttpRequest, so if you have the expertise, you may use it. Below code is the sample code of Fetch API.
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Keep in mind that Fetch API employs double promises, whereas Axios only has to use a single promise to obtain the body of the data. This is so that Fetch API can immediately return after receiving the response’s reader. The double promise style is used because the API needs to wait until the body has loaded.
Let’s now discuss how each feature of the two tools differs from the others. In this blog, we will cover the below-listed aspects of (Axios Library and Fetch API- HTTP Call Comparison).
Error Handling
There is always a potential that an error will arise when retrieving data. An error possibility that is addressed includes invalid credentials, URLs that cannot be retrieved, and server errors. We can determine whether the request is true or false by looking at the Response.ok attribute in the Fetch API. If the response falls between 200 and 299, this attribute will return true; otherwise, it will return false.
var myImage = document.querySelector('img');
var myRequest = new Request('QLlogo.jpg');
fetch(myRequest).then(function(response) {
console.log(response.ok); // returns true if the response returned successfully
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});
In contrast, Axios' error handling is comparable to that of other promise-based objects: employing a catch handler. This handler is used to match any unsuccessful requests, which will result in their rejection. The example that follows is taken directly from the Axios documentation. The example demonstrates how error handling can be divided into three categories:
The response contained an error: status code outside the 200–299 range.
Request error: A request is made but receives no response.
Other errors: inability to send the request or cannot send the request.
axios.get('/user/34567')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Timeout
You should cancel a request early if it unexpectedly takes too long to complete or process so the user knows the problem. We require timeout functionality in the fetching tools we employ to do this. This functionality is already included in Axios. Simply adding the timeout attribute to the request configuration will do.
axios({
method: 'post',
url: '/user',
timeout: 4000 // Wait until 2 second before aborting
});
While there is no built-in functionality in the Fetch API, we can utilize an interface named AbortControler in the more recent browser version. The AbortController interface allows us to terminate an active fetch request. Below is an illustration of how you might use this interface.
const controller = new AbortController();
const signal = controller.signal;
fetch("https://example.com/movies.json", {
method: 'get',
signal: signal,
})
// ... (Other code)
controller.abort(); // Now the fetch will be aborted
Compatibility
Now, let’s discuss the browser compatibility of Axios Library and Fetch API.
Axios is far more backward compatible with the early version of the browser when compared to Fetch API compatibility. This is because Axios use XMLHttpRequest on the browser side. The XMLHttpRequest documentation indicates that this functionality is compatible with prior browser iterations. You must know that the Fetch API may only function on a later version when using it. Since few people still use outdated browsers, this should be fine in most circumstances.
General
In this section, we will discuss the general differences between these two.
Fetch API employs two promises, whereas Axios uses a single promise, as we have briefly covered before. The single promise of Axios makes it more practical for use cases where the body size is not very large. Axios is more useful if your use case only involves exchanging simple JSON data. However, if you deliver a significant amount of data, such as an image, you can test the Fetch API to see whether it works for you.
The single promise approach of the Fetch API is shown in the below code.
const fetchSimple = api => fetch(api)
.then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));
fetchSimple('http://example.com/movies.json')
.then(response => response.json())
.catch(err => console.log(err));
It’s also important to note that Axios is on extra dependency while Fetch API is built-in. Fetch API would be better if you want to keep your application light.
Concurrent Request
Promise.all()
might run numerous requests concurrently using Fetch(). Similarly, Axios()
it offers a mechanism to accomplish the same task with fewer lines of code by using Axios.all
the spread operator to break the answer into different objects.
Promise.all([
fetch('https://mywebsite.com/user/getInfo'),
fetch('https://mywebsite.com/user/getFriendList')])
.then(async([res1, res2]) => {
const userInfo= await res1.json();
const userFriendList= await res2.json();
console.log(userInfo);
console.log(userFriendList);
})
.catch(error => { console.log(error);});
==== vs ====
axios.all([
axios.get('https://mywebsite.com/user/getInfo'),
axios.get('https://mywebsite.com/user/getFriendList')])
.then(axios.spread((obj1, obj2) => {
// Both requests are now complete
console.log(obj1.data);
console.log(obj2.data);
}));
Download & Upload Progress
Fetch() lets you monitor the download progress using one of the response.body
properties, a ReadableStream
object. It provides body data chunk by chunk and allows you to count how much data is consumed in time. However, Fetch() does not allow you to monitor your uploads.!!
On the other side, Axios offers a mechanism for you to keep track of your downloads and uploads. Use the Axios Progress Bar to track download progress, and for tracking upload progress, use the onUploadProgress
config parameter.
Final Takeaway
Axios makes it easy to read data that comes to your application as JSON and to make new resources in your application available on the server. Fetch can also do this, but it is much more limited. You might like one of the other APIs better, but you'll need to consider their limitations as you develop your app requirements.