Fetch or Axios, which is more suitable for HTTP requests?

created at 08-17-2021 views: 1

Introduction

One of the most important parts of front-end development is to communicate with the back-end by issuing HTTP requests. We have several ways to make API calls in JavaScript asynchronously.

A few years ago, most applications used Ajax to send HTTP requests. Ajax stands for asynchronous JavaScript and XML. But now, developers usually decide to choose between the .fetch() API and Axios.

In this article, I want to compare the two methods and briefly introduce the basic knowledge and grammar. In addition, I will compare the process of converting data to JSON format in both cases and error handling. I will also discuss HTTP interception and download progress.

let's start!

Fetch overview and syntax

When building a Javascript project, we can use the window object, and it comes with many excellent methods that can be used in the project. One of these features is the Fetch API, which provides a simple global .fetch() method, which is a logical solution for fetching data asynchronously from the API.

Let's take a look at the syntax of the .fetch() method.

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

In the above example, you can see the simple syntax to get a GET request. In the .fetch() method, we have a mandatory parameter url, which returns a Promise, which can be resolved using the Response object.

The second parameter of the .fetch() method is an option, which is optional. If we don't pass options, the request is always GET, which downloads the content from the given URL.

In the option parameter, we can pass method or header information, so if we want to use the POST method or other methods, we must use this optional array.

As I mentioned before, Promise will return a Response object, because of this, we need to use another method to get the body of the response. There are several different methods that can be used, depending on the format we need:

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

Let's take a look at a code example with optional parameters.

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 a simple POST request, including method, header, and body params. Then I use the json() method to convert the response to JSON format.

Now, let's take a closer look at axios.

Axios overview and syntax

Axios is a Javascript library used to make HTTP requests from Node.js or XMLHttpRequests or browsers. As a modern library, it is based on the Promise API.

axios has some advantages, such as protection of XSRF or cancellation of requests.

In order to be able to use the axios library, we must install and import it into our project. You can install axios using CDN, npm or bower. Now, let us 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 that I used the .get() method to create a simple GET request. If you want to use the POST method in the function, just use the .post() method instead, and pass the request data as a parameter.

When we create a configuration object, we can define a bunch of properties, the most common are:

baseUrl
params
headers
auth
responseType

In response, axios returns a promise, which will be resolved with the response object or error object. In the response object, it has the following values:

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

Now, let's take a look at a code example of the POST method with data.

axios.post({
  '/url', 
  { name: 'John', age: 22},
  { options }
})

In the above code, you can see the post method. We use the config object as a param, which contains URL, data, and additional options.

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

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

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

JSON

As mentioned earlier, when we are using the .fetch() method, we need to use a certain method for the response data. When we send the body with the request, we need to stringify the data.

In axios, it is done automatically, so we only need to pass data in the request or get data from the response. It is automatically stringified, so no other operations are required.

Let's see how to get data from fetch() and 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 above example, you can see that using axios we don't have an extra line of code. In the .fetch() example, we must convert the data to JSON format. In a larger project, if you create a large number of calls, it is more comfortable to use axios to avoid duplication of code.

Error handling

At this point, we also need to like axios, because it is very easy to deal with errors. If there is an error response like 404, the promise will be rejected and an error will be returned, so we need to catch an error, we can check what type of error it is, and that's it. Let's take a look at the code example.

axios.get('url')
  .then((response) => console.log(response))
  .catch((error) => {
    if (error.response) {
      // When response status code is out of 2xx range 
      console.log(error.response.data)
      console.log(error.response.status)
      console.log(error.response.headers)
    } else if (error.request) {
      // When no response was recieved after request was made
      console.log(error.request)
    } else {
      // Error
      console.log(error.message)
    }
  })

In the above code, I returned data when the response was good, but if the request failed in any way, I was able to check the type of error in the .catch() section and return the correct message.

For the .fetch() method, it is more complicated. Every time we get a response from the .fetch() method, we need to check whether the status is successful, because even if it is not, we will get a response. In the case of .fetch(), the promise will only be resolved if the request is not fulfilled. Let's take a look at the code example.

fetch('url')
  .then((response) => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response.json()
  })
  .then((data) => console.log(data))
  .catch((error) => console.log(error))

In this code, I have checked the status of the code in the promise object. If the response has the status ok, then I can process and use the .json() method, but if not, I must return it in .then() Mistake.

In order to facilitate and correct error handling, axios will definitely be a better solution for your project, but if you are building a small project with only one or two requests, you can use .fetch(). But you need to remember to handle errors properly.

Download progress

When we need to download a large amount of data, a way to track progress can be useful, especially when the user's network speed is slow. In the early days, in order to achieve progress indicators, developers used the XMLHttpRequest.onprogress callback. In .fetch() and axios, there are different ways to do it.

In order to track the download progress in .fetch(), we can use one of the response.body properties, a ReadableStream object. It provides the subject data block by block and allows us to calculate how much data is consumed by time.

In axios, it is also possible to implement a progress indicator, and it is easier, because there is a ready-made module that can be installed and implemented, it is called Axios Progress Bar.

If you have a lot of big data to download and you want to track the progress of the progress indicator, you can use axios to manage it, which is easier and faster, but .fetch() also provides this possibility, but it requires more code To develop the same result.

HTTP interception

When we need to check or change our HTTP request from the application to the server, or in other ways, for example, for authentication, HTTP interception may be important.

In the case of axios, HTTP interception is one of the key features of this library, which is why we don't need to create additional code to use it. Let's take a look at the code example and see how easy we can do it.

// Request interception
axios.interceptors.request.use((config) => {
  console.log('Request sent');
})
// Response interception
axios.interceptors.response.use((response) => {
  // do an operation on response
  return response
})
axios.get('url')
  .then((response) => console.log(response))
  .catch((error) => console.log(error))

In the code, you can see request interception and response interception. In the first case, I created a console.log to inform the sending of the request. In response interception, we can do any operation on the response and then return.

.fetch() does not provide HTTP interception by default. We can override the .fetch() method to define what needs to happen during the request process. Of course, this requires more code and may be more complicated than using axios.

Summarize

In this article, I compared the two methods used to create HTTP requests, starting with a simple overview, through syntax and some important functions, such as download progress or error handling.

Through comparison, it can be seen that Axios is a better solution for applications that have a large number of HTTP requests and require good error handling or HTTP interception. In the case of small projects, only a few simple API calls are required, and Fetch is also a good solution.

When choosing the best solution for the project, it is also very important to pay attention to one factor. Most browsers and Node.js environments support Axios, while modern browsers only support Fetch, and some versions may be released with older versions.

Through the understanding of this knowledge, I hope that everyone can choose the most suitable plan for them, and I hope that everyone finds this more helpful.

Please log in to leave a comment.