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

The comparison shows that Axios is a better solution for applications with a large number of HTTP requests that require good error handling or HTTP interception. Fetch is also a good solution in the case of small projects where only a few simple API calls are required. Read the original

One of the most important parts of front-end development is communicating with the back end by making HTTP requests, and there are several ways to make API calls asynchronously in Javascript.

A few years ago, most applications sent HTTP requests using Ajax, which stood for asynchronous Javascript and XML. But now, developers often decide to choose between the FETCH () API and Axios.

In this article, I want to compare the two approaches and briefly cover the basics and syntax. In addition, I’ll compare the process of converting data to JSON format in both cases and in error handling. I’ll also discuss HTTP interception and download progress.

Let’s go!

Fetch Overview and syntax

When building a Javascript project, you can use the Window object, and it comes with a number of nice methods that you can use in your project. One of these features is the Fetch API, which provides a simple global.fetch() method, which is a logical solution to get data asynchronously from the API.

Let’s look at the syntax of the.fetch() method.

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

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

The second argument to the.fetch() method is the 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 argument, we can pass method or header information, so if we want to use POST or other methods, we have to use this optional array.

As I mentioned earlier, a Promise returns a Response object, and because of that, we need to use another method to get the body of the Response. There are several different methods we can use, depending on the format we want:

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

Let’s look at an example of code with optional arguments.

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

In the code example above, you can see simple POST requests, including method, header, and body params. I then 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 that makes 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 XSRF protection or cancellation requests.

In order to be able to use the AXIOS library, we had to install and import it into our project. You can install AXIOS using CDN, NPM, or Bower. Now, let’s look at the syntax of a simple GET method.

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

In the code above, you can see that I created a simple GET request using the.get() method. If you want to use the POST method in a function, simply use the.post() method instead and pass the request data as an argument.

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

  • baseUrl
  • params
  • headers
  • auth
  • responseType

In response, AXIos returns a Promise that will be parsed with either the response object or the error object. In the response object, there are the following values:

  • Data, which is the actual response body
  • Status, the HTTP status of the call, such as 200 or 404
  • statusText, HTTP status returned as a text message, for exampleok
  • Headers, the server sends back the header
  • Config: requests the configuration
  • Request, XMLHttpRequest object

Now, let’s look at a code example of a POST method with data.

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

In the code above, you can see the POST method, and we treat the Config object as a param with the URL, data, and additional options.

We can also define the Config object as a variable and pass it to Axios as in the following example.

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

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

JSON

As mentioned earlier, when we use the.fetch() method, we need to use some method for the response data, and when we send the body with the request, we need to string the data.

In AXIos, this is done automatically, so we just need to pass the data in the request or get the data from the response. It is automatically stringed, so no other operations are required.

Let’s look at 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))
Copy the code

In the example above, you can see that with Axios we don’t have an extra line of code, and in the case of.fetch() we have to convert the data to JSON format. On a larger project, if you’re creating a lot of calls, it’s more comfortable to use Axios to avoid duplicate code.

Error handling

Give Axios credit at this point, too, because it’s so easy to handle errors. If an error response like 404 occurs, the promise is rejected and an error is returned, so we need to catch an error, and we can check what type of error it is, and that’s it. Let’s look at a 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)
    }
  })
Copy the code

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

The.fetch() method is more complicated. Every time we get a response from the.fetch() method, we need to check if the status is successful, because even if it isn’t, we’ll get the response. In the case of.fetch(), the promise is resolved only if the request is not completed. Let’s look at a 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))
Copy the code

In this code, I have checked the state of the code in the promise object. If the response is stateful OK, then I can process and use the.json() method, but if not, I must return an error in.then().

Axios would definitely be a better solution for your project for convenience and correct error handling, but if you’re building a small project with only one or two requests, using.fetch() is fine, but you need to remember to handle errors correctly.

Download progress

When we need to download large amounts of data, a way to track progress can be useful, especially if the user has a slow network. At the early stage, in order to achieve the progress indicator, developers use the XMLHttpRequest. Onprogress callback. In.fetch() and Axios, there are different ways to do this.

To track the download progress in.fetch(), we can use one of the Response.body attributes, a ReadableStream object. It provides the body data piece by piece and allows us to calculate how much data is consumed over time.

It is also possible to implement a Progress indicator in AXIos, and it is easier because there is a ready-made module that you can install and implement called the Axios Progress Bar.

If you have a lot of big data to download and you want to track the progress of progress metrics, you can manage it with Axios, much easier and faster, but.fetch() also offers this possibility, it just takes more code to develop the same results.

Intercept the HTTP

HTTP interception may be important when we need to examine or change our HTTP requests from the application to the server, or in other ways, for example, for validation purposes.

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 look at a code example to see how easy we can do this.

// 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))
Copy the code

In the code, you can see request interception and response interception. In the first case, I create a console.log that tells me when to send the request, and in response interception, we can do anything with the response and then return.

.fetch() does not provide HTTP interception by default, we can override the.fetch() method and define what needs to happen during the sending of the request, which of course requires more code and may be more complex than using axios functionality.

conclusion

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

The comparison shows that Axios is a better solution for applications with a large number of HTTP requests that require good error handling or HTTP interception. Fetch is also a good solution in the case of small projects where only a few simple API calls are required.

It is important to note another factor when choosing the best solution for a project. Most browsers and Node.js environments support Axios, while modern browsers only support Fetch, and some versions may be shipped with older versions.

Through the understanding of these knowledge, I hope you can choose the most suitable scheme for their own, but also hope that you feel this is more helpful.

Thanks for reading ❤


Pay attention to hair loss, stall stall,Selling goodsContinuous learning programmers, the first time to read the latest articles, will be two days before the publication of new articles. Attention can receive the gift package, you can save a lot of money!