Performing HTTP Requests: Fetch Vs Axios

Comparing the Fetch API and the Axios library

In JavaScript, Fetch API and Axios are widely used to implement HTTP requests. But, choosing one isn’t easy since they both have some unique features.

In this article, I will discuss the highlights of Fetch API and Axios to see the best option for HTTP requests.

1. Syntax Differences

Both Axios and Fetch API returns Promises when you make an HTTP request. Although, there are some differences in the syntax.

The below code shows how we can send a simple POST request with Axios.

https://medium.com/media/7243741f4a43555fd8ee65a5e556ae85/href

With Axios, we can create a config object using specified parameters like baseUrl, params, headers, auth, responseType to send with the request. It will return a Promise that resolves with either a response object or an error object. Besides, the following can be found in the returned object from the Promise.

  • data:- the actual response body
  • status:- HTTP status of the call, like 200 or 404
  • statusText:- HTTP status returned as a text message
  • headers:- the server sends headers back
  • config:- request configuration
  • request:- XMLHttpRequest object

If we try the same POST with Fetch API, it will look like this:

https://medium.com/media/8a607934ec66dc7afb5d285716ba704d/href

The url (path to the resource you want to fetch) argument is mandatory in the fetch() method. Similar to Axios, it returns a Promise that the response object can resolve. We can optionally pass options in the second argument in the fetch() method.

Key Differences:

  • With Axios, the data is sent through the data property of the options, but Fetch API uses the body property.
  • Fetch response requires additional validation as it always returns a response object no matter whether it is successful or not.
  • The data in fetch() has been serialized to a String (Stringified).
  • The URL is provided to fetch() as an argument. But, in Axios, it is set in the options object.

2. JSON Data Conversion

With Fetch API, handling JSON data is a 2 step process. First, you must make the request and then call the .json() function on the response since Fetch API sends data with the body property.

https://medium.com/media/14e010e74c7223c530467ddeb5b73f26/href

With Axios, the data is sent through the data property of the options, and it automatically stringifies the data in the response. So, we don’t have to do a lot there as Axios inevitably converts JSON data after the request is resolved.

https://medium.com/media/0a3589751753240593e7c05ad3dc361c/href

3. Error Handling

Error handling with Axios is easy because bad responses (such as 404 or 500) will end up causing the Promise to be rejected by throwing an exception. Therefore, to handle 404 or 400 errors with Axios, you need to use the catch() block as shown below.

https://medium.com/media/2dd7d714ed24d7df02f08b1d7033be92/href

When using fetch(), you need to read the response object since bad responses are still resolved using the then() method. A Fetch API Promise will be rejected only if the request cannot be completed in a scenario like a network failure.

https://medium.com/media/0ed6f5fcbe5f4e226de5e55bf62334cf/href

4. Simultaneous Requests

Both Axios and Fetch API can handle multiple requests in parallel. Axios uses the axios.all() method that allows passing an array of requests. Then assign the properties of the response array to distinct variables using axios.spread() as shown here.

https://medium.com/media/82a5178d452c0c503f9e1838725c6d87/href

With Fetch API, you can use the built-in Promise.all() method to accomplish the same by passing all fetch requests to Promise.all() as an array. Next, you can use an async function to handle the response as follows.

https://medium.com/media/36c3cdf997cdceb13350bad0acb6df44/href

5. Response timeout

If you make a request without defining a timeout it will cause the request to hang and slow down the application. So, we need to set a response timeout for HTTP requests.

In Axios, you can set response time in milliseconds as an optional parameter in the config object.

https://medium.com/media/b72a1d32f91814cda0ab2b44ad30b7af/href

But in Fetch API, it is not simple as in Axios.

https://medium.com/media/320d8097f6c507614110427de2d34412/href

From the above example, you can see that fetch() response timeout functionality through AbortController interface. In addition, the read-only signal property of AbortController allows you to interact with or abort a request.

If the server doesn’t respond within the specified time(3 seconds), controller.abort() is invoked, and the request is aborted.

Axios sets the timeout to 0 by default. So, always remember to specify a timeout for each request. You may also use a request interceptor to set the request timeout automatically.

6. Intercepting Requests and Responses

In web applications, there are situations where we need to intercept HTTP requests. For example, we might need to append a customized token to an HTTP request.

Using Axios can become handy in such situations since it comes with a built-in feature called HTTP interceptor. It eliminates the need to code for each request separately and you can easily use it as follows:

https://medium.com/media/ca9b0e598fb69270a636af3054e7f6a6/href

Fetch API doesn’t offer a way to intercept requests by default.

But, as a workaround, you can implement your own interceptor by overriding the global fetch() method:

https://medium.com/media/3736604858aeafc5270e05816e40bbfa/href

7. Request Upload/Download Progress

If your HTTP request takes a significant time to complete, using a progress indicator will surely help to improve the user experience.

If you use Axios, you can easily use the Axios Progress Bar module to implement a nice progress indicator.

First, add the following style and script tags to your component.

https://medium.com/media/030271da56875a614b702d61db821b55/href

Then you can implement the progress bar as below. That’s it.

https://medium.com/media/0397b6d0ca4e6c6fdeb8243efe2c8a7d/href

But Fetch API doesn’t have in-built support for progress bars.

Instead, it offers a ReadableStream instance, that provides response.body data in chunks. It gives instant feedback to users during a download or an upload, and you can use that stream to keep track of the progress.

https://medium.com/media/ae98499c9019c557457c0ebe2e29a8eb/href

Conclusion

In this article, I evaluated two approaches for making HTTP requests, Axios and Fetch API.

This comparison demonstrates that Axios keeps the code minimal for applications that require efficient error handling or HTTP interceptions. it supports almost all modern browsers and NodeJS environments.

On the other hand, Fetch API isn’t far off either as a native method supported by all the major browsers (it doesn’t support IE).

However, we can not stick to a single aspect in choosing the best option. Instead, you need to evaluate all these features and decide what’s best for your project based on its requirements.

Thank you for reading….!!!

Build better Component Libs and Design Systems

Share components across teams and projects to speed up development and make sure your users experience a consistent design at every touchpoint.

OSS Tools like Bit offer a great dev experience for building, sharing, and adopting components across teams and applications. Create a component hub for free give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn More


Performing HTTP Requests: Fetch Vs Axios was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana

Comparing the Fetch API and the Axios library

In JavaScript, Fetch API and Axios are widely used to implement HTTP requests. But, choosing one isn’t easy since they both have some unique features.

In this article, I will discuss the highlights of Fetch API and Axios to see the best option for HTTP requests.

1. Syntax Differences

Both Axios and Fetch API returns Promises when you make an HTTP request. Although, there are some differences in the syntax.

The below code shows how we can send a simple POST request with Axios.

With Axios, we can create a config object using specified parameters like baseUrl, params, headers, auth, responseType to send with the request. It will return a Promise that resolves with either a response object or an error object. Besides, the following can be found in the returned object from the Promise.

  • data:- the actual response body
  • status:- HTTP status of the call, like 200 or 404
  • statusText:- HTTP status returned as a text message
  • headers:- the server sends headers back
  • config:- request configuration
  • request:- XMLHttpRequest object

If we try the same POST with Fetch API, it will look like this:

The url (path to the resource you want to fetch) argument is mandatory in the fetch() method. Similar to Axios, it returns a Promise that the response object can resolve. We can optionally pass options in the second argument in the fetch() method.

Key Differences:

  • With Axios, the data is sent through the data property of the options, but Fetch API uses the body property.
  • Fetch response requires additional validation as it always returns a response object no matter whether it is successful or not.
  • The data in fetch() has been serialized to a String (Stringified).
  • The URL is provided to fetch() as an argument. But, in Axios, it is set in the options object.

2. JSON Data Conversion

With Fetch API, handling JSON data is a 2 step process. First, you must make the request and then call the .json() function on the response since Fetch API sends data with the body property.

With Axios, the data is sent through the data property of the options, and it automatically stringifies the data in the response. So, we don’t have to do a lot there as Axios inevitably converts JSON data after the request is resolved.

3. Error Handling

Error handling with Axios is easy because bad responses (such as 404 or 500) will end up causing the Promise to be rejected by throwing an exception. Therefore, to handle 404 or 400 errors with Axios, you need to use the catch() block as shown below.

When using fetch(), you need to read the response object since bad responses are still resolved using the then() method. A Fetch API Promise will be rejected only if the request cannot be completed in a scenario like a network failure.

4. Simultaneous Requests

Both Axios and Fetch API can handle multiple requests in parallel. Axios uses the axios.all() method that allows passing an array of requests. Then assign the properties of the response array to distinct variables using axios.spread() as shown here.

With Fetch API, you can use the built-in Promise.all() method to accomplish the same by passing all fetch requests to Promise.all() as an array. Next, you can use an async function to handle the response as follows.

5. Response timeout

If you make a request without defining a timeout it will cause the request to hang and slow down the application. So, we need to set a response timeout for HTTP requests.

In Axios, you can set response time in milliseconds as an optional parameter in the config object.

But in Fetch API, it is not simple as in Axios.

From the above example, you can see that fetch() response timeout functionality through AbortController interface. In addition, the read-only signal property of AbortController allows you to interact with or abort a request.

If the server doesn't respond within the specified time(3 seconds), controller.abort() is invoked, and the request is aborted.

Axios sets the timeout to 0 by default. So, always remember to specify a timeout for each request. You may also use a request interceptor to set the request timeout automatically.

6. Intercepting Requests and Responses

In web applications, there are situations where we need to intercept HTTP requests. For example, we might need to append a customized token to an HTTP request.

Using Axios can become handy in such situations since it comes with a built-in feature called HTTP interceptor. It eliminates the need to code for each request separately and you can easily use it as follows:

Fetch API doesn’t offer a way to intercept requests by default.

But, as a workaround, you can implement your own interceptor by overriding the global fetch() method:

7. Request Upload/Download Progress

If your HTTP request takes a significant time to complete, using a progress indicator will surely help to improve the user experience.

If you use Axios, you can easily use the Axios Progress Bar module to implement a nice progress indicator.

First, add the following style and script tags to your component.

Then you can implement the progress bar as below. That’s it.

But Fetch API doesn’t have in-built support for progress bars.

Instead, it offers a ReadableStream instance, that provides response.body data in chunks. It gives instant feedback to users during a download or an upload, and you can use that stream to keep track of the progress.

Conclusion

In this article, I evaluated two approaches for making HTTP requests, Axios and Fetch API.

This comparison demonstrates that Axios keeps the code minimal for applications that require efficient error handling or HTTP interceptions. it supports almost all modern browsers and NodeJS environments.

On the other hand, Fetch API isn’t far off either as a native method supported by all the major browsers (it doesn’t support IE).

However, we can not stick to a single aspect in choosing the best option. Instead, you need to evaluate all these features and decide what’s best for your project based on its requirements.

Thank you for reading….!!!

Build better Component Libs and Design Systems

Share components across teams and projects to speed up development and make sure your users experience a consistent design at every touchpoint.

OSS Tools like Bit offer a great dev experience for building, sharing, and adopting components across teams and applications. Create a component hub for free give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn More


Performing HTTP Requests: Fetch Vs Axios was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana


Print Share Comment Cite Upload Translate Updates
APA

Piumi Liyana Gunawardhana | Sciencx (2021-10-07T17:49:49+00:00) Performing HTTP Requests: Fetch Vs Axios. Retrieved from https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/

MLA
" » Performing HTTP Requests: Fetch Vs Axios." Piumi Liyana Gunawardhana | Sciencx - Thursday October 7, 2021, https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/
HARVARD
Piumi Liyana Gunawardhana | Sciencx Thursday October 7, 2021 » Performing HTTP Requests: Fetch Vs Axios., viewed ,<https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/>
VANCOUVER
Piumi Liyana Gunawardhana | Sciencx - » Performing HTTP Requests: Fetch Vs Axios. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/
CHICAGO
" » Performing HTTP Requests: Fetch Vs Axios." Piumi Liyana Gunawardhana | Sciencx - Accessed . https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/
IEEE
" » Performing HTTP Requests: Fetch Vs Axios." Piumi Liyana Gunawardhana | Sciencx [Online]. Available: https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/. [Accessed: ]
rf:citation
» Performing HTTP Requests: Fetch Vs Axios | Piumi Liyana Gunawardhana | Sciencx | https://www.scien.cx/2021/10/07/performing-http-requests-fetch-vs-axios/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.