Frontend Development: fetch vs. axios

Peter Jeon·2023년 6월 29일
0

Frontend Development

목록 보기
37/80
post-custom-banner

When it comes to making HTTP requests in JavaScript, developers have a choice between using the built-in fetch function or utilizing a third-party library such as axios. Both options have their own strengths and weaknesses.

Featurefetchaxios
Promise-basedYesYes
Support for request cancellationNoYes
Support for upload progressNoYes
Automatic JSON data transformationNoYes
Can be used on the serverNoYes

fetch

The fetch API is a built-in browser API for making HTTP requests. It's promise-based, which makes it more readable and manageable.

Here's an example of how you might use fetch:

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

axios

Axios is a third-party library that you can use to make HTTP requests. It's also promise-based and offers a host of additional features over fetch, including automatic JSON data transformation and the ability to cancel requests.

Here's an example of how you might use axios:

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

Conclusion

Both fetch and axios are powerful tools for making HTTP requests in JavaScript. While fetch is built into the browser, axios provides additional functionality and can also be used on the server with Node.js.

Choosing between fetch and axios often comes down to the needs of your project. For simpler use cases, fetch may be sufficient, but for more complex scenarios, especially those that require extra features such as request cancellation and upload progress, axios may be the better choice. The ability to use axios on both the client and server also makes it a flexible option for full-stack JavaScript developers.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글