Wednesday, June 29, 2022
HomeTechnologyWhy JavaScript Developers Should Prefer Axios Over Fetch | by Sabesan Sathananthan

Why JavaScript Developers Should Prefer Axios Over Fetch | by Sabesan Sathananthan


Fetch

Fetch() is part of a JavaScript window-object method within the Fetch API. It is built in, so users don’t have to install it. Fetch() allows us to get data from the API asynchronously without installing any additional libraries.

The above piece of code is a simple fetch() get request. In the fetch() method, there’s one mandatory argument, which is url. url is a path from which the user would like to get data. Then fetch() method returns a promise that can resolve the response object or reject it with an error.

The second arguments in the fetch() method are options, and they’re optional. If the user won’t pass the options, the request always gets, and it downloads the content from the given URL. As I mentioned before, the promise returns the response object, and because of that, users need to use another method to get a body of the response. There are a few different methods that users can use depending on the format of the body.

  • response.json()
  • response.text()
  • response.blob()
  • response.formData()
  • response.arrayBuffer()

The most popular one is response.json().

Unfortunately, the built-in fetch() function is not in Node.js, but there is a polyfill like node-fetch. Between node-fetch and the browser fetch(), there exist several known variations.

Axios

Axios is a JavaScript library for making HTTP requests from Node or XMLHttpRequest or a browser. As a modern library, it’s based on the Promise API. Axios has some advantages, like protection against cross-site request forgery (CSFR) attacks. To be able to use the Axios library, users have to install it and import it to your project, using CDN, npm, Yarn, or Bower.

The above piece of code is a get method and a simple callback for a response and an error. When users are creating a config object, they can define a bunch of properties. The most common are url, baseURL, params, auth, headers, responseType, and data.

As a response, Axios returns a promise that’ll resolve with the response object or an error object. In the response object, there are the following values:

  • data: Actual response body
  • status: HTTP status code of the call, like 200 or 404
  • statusText: HTTP status as a text message
  • headers: The same as in the request
  • config: Request configuration
  • request: XMLHttpRequest (XHR) object

Users need to work with two promises in fetch(). Users can avoid boilerplate and write cleaner, more succinct code in Axios.

Axios uses the data property, but fetch() uses the body property to deal with data. fetch()’s data is stringified. In fetch(), the URL is passed as an argument, but in Axios the URL is set in the config object.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments