What is better for HTTP requests: Fetch or Axios comparison

What is better for HTTP requests: Fetch or Axios comparison

Overview, JSON data, Error handling, HTTP interception, Response Timeout, Simultaneous Requests, Download progress, Upload progress, Browser support

Overview Fetch -- The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

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.

TheFetch() method takes one mandatory argument - the path to the resource you want to fetch- and returns a Promise that resolves with an object of the built-in Response class as soon as the server responds with headers. Let's take a look at the syntax of the fetch() method.

fetch(url)
  .then((res) => 
    // handle response
  )
  .catch((error) => {
    // handle error
  })

The second argument in fetch() method are options, and it's optional. If we won't pass the options the request is always GET, and it downloads the content from the given URL. Inside the options parameter, we can pass methods or headers, so if we would like to use the POST method or any other, we have to use this optional array.

{
  method: 'POST', // *GET, POST, PUT, DELETE, etc.
  mode: 'cors', // no-cors, *cors, same-origin
  cache: 'no-cache', 
   // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'same-origin', // include, *same-origin, omit
  headers: { 
    'Content-Type': 'application/json'
  },
  redirect: 'follow', // manual, *follow, error
  referrerPolicy: 'no-referrer', // no-referrer, *client
  body: JSON.stringify(data) 
   // body data type must match "Content-Type" header
}

Once a Response is retrieved, the returned object contains the following properties:

  • response.body: A simple getter exposing a ReadableStream of body contents.

  • response.bodyUsed: Stores a Boolean that declares whether the body has been used in response yet.

  • response.headers: The headers object associated with the response

  • response.ok: A Boolean indicating whether the response was successful or not

  • response.status: The status code of the response.

-response.type: The type of the response

-response.url: The URL of the response

There are a few different methods that we can use, depends on the format of the body that we need: response.json(), response.text(), response.formData(),response.blob(), response.arrayBuffer().

Let's take a took at the code example with an optional parameter.

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
});
  .then((response) => response.json())
  .catch((error) => console.log(error))

In the code example above, you can see the simple POST request with the method, header, and body params.

Axios - Axios is a JavaScript library used to make HTTP requests from node.js or XMLHTTPRequests from the browser, and it supports the Promise API that is native to JS ES6

Some core features of Axios, according to the documentation, are:

  • It can be used to intercept HTTP requests and responses.
  • It automatically transforms request and response data.
  • It enables client-side protection against CSRF
  • It has built-in support for the download process
  • It has the ability to cancel requests.

To be able to use axios library, we have to install it and import it to our project. axios can be installed using CDN, npm, or bower. Now let's take a look at the syntax of a simple GET method.

axios.get(url)
  .then(response => console.log(response));
  .catch((error) => console.log(error));

In the code above, you can see how axios is used to create a simple GET request using .get() method. If you'd like to use the POST method in the function, then it's enough to use post() method instead and pass the request data as a parameter.

Axios also provides more functions to make other network requests as well, matching the HTTP verbs that you wish to execute, such as:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url, data[, config])
  • axios.put(url, [data[, config]])
  • axios.patch(url, [, data[, config]]) When we are creating a config object we can define a bunch of properties, the most common are: baseUrl, params, headers, auth, responseType

As a response, axios returns a promise that will resolve with the response object or an error object. The response from a request contains the following information:

  • response.data: The response provided by the server
  • response.status: The HTTP status code from the server response, like 200 or 404.
  • response.statusText: HTTP status message from the server response, from example, ok
  • response.headers: The headers that the server responded with
  • response.config: The config that was provided to axios for the request
  • response.request: The request that generated this response

Let's take a look at the code example with the POST method with data.

axios.post({
  '/url', 
  { name: 'Ayush', age: 30},
  { options }
})

In the code above, you can see the post method, where we put the config object as a param, with URL, data, and additional options.

We can also define the config object as a variable and pass it to the axios like in the example below.

const config = {
  url: 'http://api.com',
  method: 'POST',
  header: {
    'Content-Type': 'application/json'
  },
  data: {
    name: 'Ayush',
    age: 30
  }
}
axios(config);

Here, you can see that all the parameters, including URL, data, or method, are in the config object, so it may be easier to define everything in one place.

JSON data

Fetch - There is a two-step process when handling JSON data with fetch(). First, we have to make the actual request, and then we call the .json() method on the response i.e we need to use some kind of method on the response data, and when we are sending the body with the request, we need to stringify the data.

Axios - In Axios It's done automatically, so we just pass data in the request or get data from the response. It's automatically stringified, so no other operations are required.

Let's see how we can get data from fetch and from Axios:

// fetch
fetch('url')
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error))

// axios
axios.get('url')
  .then((response) => console.log(response))
  .catch((error) => console.log(error))

In the example above, you can see that with Axios we don't have an additional line of code, where we have to convert data to JSON format, and we have this line in fetch() example. In the case of a bigger project where you create a lot of calls, it's more comfortable to use Axios to avoid repeating the code.

Source: towardsdev.com/what-is-better-for-http-requ..