Fetch or Axios — Which to Select for HTTP Requests?

One of the most essential parts of frontend development is communication with the backend by making HTTP requests. There are a few ways how we can make API calls in Javascript asynchronously.

A few years ago, most applications were sending HTTP requests using Ajax, which stands for Asynchronous Javascript and XML. But right now, developers mostly decide about selection between fetch() API and Axios.

In this article, I’d like to compare those two methods, go through basic overview and syntax. Besides that, I’ll compare the process of converting data to JSON format in both cases and error handling as well. I’m also going to talk about HTTP interception and download progress.

#javascript

What is GEEK

Buddha Community

Fetch or Axios — Which to Select for HTTP Requests?
James Ellis

James Ellis

1573121091

HTTP requests using Axios

The most common way for frontend programs to communicate with servers is through the HTTP protocol. You are probably familiar with the Fetch API and the XMLHttpRequest interface, which allow you fetch resources and make HTTP requests.

If you are using a JavaScript library, chances are it comes with a client HTTP API. jQuery’s $.ajax() function, for example, has been particularly popular with frontend developers. But as developers move away from such libraries in favor of native APIs, dedicated HTTP clients have emerged to fill the gap.

In this post we will take a good look at Axios, a client HTTP API based on the XMLHttpRequest interface provided by browsers, and examine the key features that has contributed to its rise in popularity among frontend developers.

Why Axios?

As with Fetch, Axios is promise-based. However, it provides a more powerful and flexible feature set. Advantages over the native Fetch API include:

  • Request and response interception
  • Streamlined error handling
  • Protection against XSRF
  • Support for upload progress
  • Response timeout
  • The ability to cancel requests
  • Support for older browsers
  • Automatic JSON data transformation

Installation

You can install Axios using:

  • npm:
$ npm install axios
  • The Bower package manager:
$ bower install axios
  • Or a content delivery network:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Making requests

Making an HTTP request is as easy as passing a config object to the Axios function. In its simplest form, the object must have a url property; if no method is provided, GET will be used as the default value. Let’s look at a simple example:

// send a POST request
axios({
  method: 'post',
  url: '/login',
  data: {
    firstName: 'Finn',
    lastName: 'Williams'
  }
});

This should look familiar to those who have worked with jQuery’s $.ajax function. This code is simply instructing Axios to send a POST request to /login with an object of key/value pairs as its data. Axios will automatically convert the data to JSON and send it as the request body.

Shorthand methods

Axios also provides a set of shorthand methods for performing different types of requests. The methods are as follows:

  • 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]])

For instance, the following code shows how the previous example could be written using the axios.post() method:

axios.post('/login', {
  firstName: 'Finn',
  lastName: 'Williams'
});

Handling the response

Once an HTTP request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service. To handle the result, you can use the then() method like this:

axios.post('/login', {
  firstName: 'Finn',
  lastName: 'Williams'
})
.then((response) => {
  console.log(response);
}, (error) => {
  console.log(error);
});

If the promise is fulfilled, the first argument of then() will be called; if the promise is rejected, the second argument will be called. According to the documentation, the fulfillment value is an object containing the following information:

{
  // `data` is the response that was provided by the server
  data: {},
 
  // `status` is the HTTP status code from the server response
  status: 200,
 
  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',
 
  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},
 
  // `config` is the config that was provided to `axios` for the request
  config: {},
 
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

As an example, here’s how the response looks when requesting data from the GitHub API:

axios.get('https://api.github.com/users/mapbox')
  .then((response) => {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

// logs:
// => {login: "mapbox", id: 600935, node_id: "MDEyOk9yZ2FuaXphdGlvbjYwMDkzNQ==", avatar_url: "https://avatars1.githubusercontent.com/u/600935?v=4", gravatar_id: "", …}
// => 200
// => OK
// => {x-ratelimit-limit: "60", x-github-media-type: "github.v3", x-ratelimit-remaining: "60", last-modified: "Wed, 01 Aug 2018 02:50:03 GMT", etag: "W/"3062389570cc468e0b474db27046e8c9"", …}
// => {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}

Making simultaneous requests

One of Axios’ more interesting features is its ability to make multiple requests in parallel by passing an array of arguments to the axios.all() method. This method returns a single promise object that resolves only when all arguments passed as an array have resolved. Here’s a simple example:

// execute simultaneous requests 
axios.all([
  axios.get('https://api.github.com/users/mapbox'),
  axios.get('https://api.github.com/users/phantomjs')
])
.then(responseArr => {
  //this will be executed only when all requests are complete
  console.log('Date created: ', responseArr[0].data.created_at);
  console.log('Date created: ', responseArr[1].data.created_at);
});

// logs:
// => Date created:  2011-02-04T19:02:13Z
// => Date created:  2017-04-03T17:25:46Z

This code makes two requests to the GitHub API and then logs the value of the created_at property of each response to the console. Keep in mind that if any of the arguments rejects then the promise will immediately reject with the reason of the first promise that rejects.

For convenience, Axios also provides a method called axios.spread() to assign the properties of the response array to separate variables. Here’s how you could use this method:

axios.all([
  axios.get('https://api.github.com/users/mapbox'),
  axios.get('https://api.github.com/users/phantomjs')
])
.then(axios.spread((user1, user2) => {
  console.log('Date created: ', user1.data.created_at);
  console.log('Date created: ', user2.data.created_at);
}));

// logs:
// => Date created:  2011-02-04T19:02:13Z
// => Date created:  2017-04-03T17:25:46Z

The output of this code is the same as the previous example. The only difference is that the axios.spread() method is used to unpack values from the response array.

Sending custom headers

Sending custom headers with Axios is very straightforward. Simply pass an object containing the headers as the last argument. For example:

const options = {
  headers: {'X-Custom-Header': 'value'}
};

axios.post('/save', { a: 10 }, options);

Transforming requests and responses

By default, Axios automatically converts requests and responses to JSON. But it also allows you to override the default behavior and define a different transformation mechanism. This ability is particularly useful when working with an API that accepts only a specific data format such as XML or CSV.

To change the request data before sending it to the server, set the transformRequest property in the config object. Note that this method only works for PUT, POST, and PATCH request methods. Here’s how you can do that:

const options = {
  method: 'post',
  url: '/login',
  data: {
    firstName: 'Finn',
    lastName: 'Williams'
  },
  transformRequest: [(data, headers) => {
    // transform the data

    return data;
  }]
};

// send the request
axios(options);

To modify the data before passing it to then() or catch(), you can set the transformResponse property:

const options = {
  method: 'post',
  url: '/login',
  data: {
    firstName: 'Finn',
    lastName: 'Williams'
  },
  transformResponse: [(data) => {
    // transform the response

    return data;
  }]
};

// send the request
axios(options);

Intercepting requests and responses

HTTP Interception is a popular feature of Axios. With this feature, you can examine and change HTTP requests from your program to the server and vice versa, which is very useful for a variety of implicit tasks, such as logging and authentication.

At first glance, interceptors look very much like transforms, but they differ in one key way: unlike transforms, which only receive the data and headers as arguments, interceptors receive the entire response object or request config.

You can declare a request interceptor in Axios like this:

// declare a request interceptor
axios.interceptors.request.use(config => {
  // perform a task before the request is sent
  console.log('Request was sent');

  return config;
}, error => {
  // handle the error
  return Promise.reject(error);
});

// sent a GET request
axios.get('https://api.github.com/users/mapbox')
  .then(response => {
    console.log(response.data.created_at);
  });

This code logs a message to the console whenever a request is sent then waits until it gets a response from the server, at which point it prints the time the account was created at GitHub to the console. One advantage of using interceptors is that you no longer have to implement tasks for each HTTP request separately.

Axios also provides a response interceptor, which allows you to transform the responses from a server on their way back to the application:

// declare a response interceptor
axios.interceptors.response.use((response) => {
  // do something with the response data
  console.log('Response was received');

  return response;
}, error => {
  // handle the response error
  return Promise.reject(error);
});

// sent a GET request
axios.get('https://api.github.com/users/mapbox')
  .then(response => {
    console.log(response.data.created_at);
  });

Client-side support for protection against XSRF

Cross-site request forgery (or XSRF for short) is a method of attacking a web-hosted app in which the attacker disguises himself as a legal and trusted user to influence the interaction between the app and the user’s browser. There are many ways to execute such an attack, including XMLHttpRequest.

Fortunately, Axios is designed to protect against XSRF by allowing you to embed additional authentication data when making requests. This enables the server to discover requests from unauthorized locations. Here’s how this can be done with Axios:

const options = {
  method: 'post',
  url: '/login',
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
};

// send the request
axios(options);

While Axios has some features for debugging requests and responses, making sure Axios continues to serve resources to your app in production is where things get tougher. If you’re interested in ensuring requests to the backend or 3rd party services are successful, try LogRocket. [LogRocket Dashboard Free Trial Banner

This is image title

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic Axios requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, and slow network requests as well as logs Redux, NgRx. and Vuex actions/state. Start monitoring for free.

Monitoring POST request progress

Another interesting feature of Axios is the ability to monitor request progress. This is especially useful when downloading or uploading large files. The provided example in the Axios documentation gives you a good idea of how that can be done. But for the sake of simplicity and style, we are going to use the Axios Progress Bar module in this tutorial.

The first thing we need to do to use this module is to include the related style and script:

<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/nprogress.css" />

<script src="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/index.js"></script>

Then we can implement the progress bar like this:

loadProgressBar()

const url = 'https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif';

function downloadFile(url) {
  axios.get(url)
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })
}

downloadFile(url);

To change the default styling of the progress bar, we can override the following style rules:

#nprogress .bar {
    background: red !important;
}

#nprogress .peg {
    box-shadow: 0 0 10px red, 0 0 5px red !important;
}

#nprogress .spinner-icon {
    border-top-color: red !important;
    border-left-color: red !important;
}

Canceling requests

In some situations, you may no longer care about the result and want to cancel a request that’s already sent. This can be done by using a cancel token. The ability to cancel requests was added to Axios in version 1.5 and is based on the cancelable promises proposal. Here’s a simple example:

const source = axios.CancelToken.source();

axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', {
  cancelToken: source.token
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log(thrown.message);
  } else {
    // handle error
  }
});

// cancel the request (the message parameter is optional)
source.cancel('Request canceled.');

You can also create a cancel token by passing an executor function to the CancelToken constructor, as shown below:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', {
  // specify a cancel token
  cancelToken: new CancelToken(c => {
    // this function will receive a cancel function as a parameter
    cancel = c;
  })
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log(thrown.message);
  } else {
    // handle error
  }
});

// cancel the request
cancel('Request canceled.');

Libraries

Axios’ rise in popularity among developers has resulted in a rich selection of third-party libraries that extend its functionality. From testers to loggers, there’s a library for almost any additional feature you may need when using Axios. Here are some popular libraries currently available:

#Axios #programming #HTTP #HTTP requests

6 Things About HTTP Request in Dart For Beginners

Introduction

If you are here and a beginner, that means you want to learn everything about making an API request using Dart in Flutter, then you are in the right place for the HTTP tutorial. So without wasting any time, let’s start with this flutter tutorial. We will cover the essential topics required to work with the HTTP request in Dart.

What is Rest API in Dart ?

rest api flow

Rest APIs are a way to fetch data from the internet in flutter or communicate the server from the app and get some essential information from your server to the app. This information can be regarding your app’s data, user’s data, or any data you want to share globally from your app to all of your users.

This HTTP request fetches in a unique JSON format, and then the information is fetched from the JSON and put in the UI of the app.

Every programming language has a way of some internet connectivity i.e, use this rest API developed on the server and fetch data from the internet. To use this request feature, we have to add HTTP package in flutter, add this flutter package add in your project to use the http feature. Add this HTTP package to your pubspec.yaml, and run a command in terminal :

flutter packages get

#dart #flutter #async await #async function #cancel http api request in flutter #fetch data from the internet #flutter cancel future #flutter get request example #flutter post request example #future of flutter #http tutorial

Fetch or Axios - what is better for HTTP requests?

This article was originally published at https://www.blog.duomly.com/fetch-vs-axios-what-is-better-in-2020/


Intro to Fetch vs. Axios

One of the most essential parts of frontend development is communication with the backend by making HTTP requests. There are a few ways how we can make API calls in Javascript asynchronously.

A few years ago, most applications were sending HTTP requests using Ajax, which stands for Asynchronous Javascript and XML. But right now, developers mostly decide about selection between fetch() API and Axios.

In this article, I’d like to compare those two methods, go through basic overview and syntax. Besides that, I’ll compare the process of converting data to JSON format in both cases and error handling as well. I’m also going to talk about HTTP interception and download progress.

Let’s start!

Fetch overview and syntax

When we are building a Javascript project, we can use a window object, and it comes with many great methods that we can use in the project. One of those features is Fetch API, which provides an easy, global .fetch() method, which is a logic solution to fetch data from the API asynchronously.

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

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

In the example above, you can see the syntax of a simple fetch GET request. In .fetch() method, we have one mandatory argument url. It returns a Promise, which can resolve with the Response object.

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.

As I mentioned before, the Promise returns the Response object, and because of that, we need to use another method to get the body 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 look 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 method, header, and body params. Then I use json() method to convert the response to JSON format.

Now, let’s take a closer look at the axios.

Axios overview and syntax

Axios is a Javascript library for making HTTP requests from Node.js or XMLHttpRequests or browser. As a modern library, it’s based on Promise API.

axios has some advantages that are like protection against XSRF or canceling 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 I user axios 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.

When we are creating a config object we can define 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. In the response object, there are the following values:

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

Right now, let’s take a look at the code example with the POST method with data.

axios.post({
  '/url', 
  { name: 'John', age: 22},
  { 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: 'John',
    age: 22
  }
}

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

As I mentioned before, when we are using .fetch() method, 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.

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.

Error handling

At this point, we also need to give points for axios as handling errors is pretty easy. If there will be a bad response like 404, the promise will be rejected and will return an error, so we need to catch an error, and we can check what kind of error it was, that’s it. Let’s see 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 code above, I’ve 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 .catch() part and return the proper message.

With the .fetch() method, it’s a little bit more complicated. Every time we get a response from the .fetch() method, we need to check if the status is a success because even if it’s not, we will get the response. In case of .fetch() promise won’t be resolved only when the request won’t be completed. Let’s see 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’ve checked the status of the code in the promise object, and if the response had status ok, then I could process and use .json() method, but if not, I had to return error inside .then().

For easy and proper error handling, axios will be definitely a better solution for your project, but still, if you are building a small project with one or two requests, it’s fine to use .fetch(), but you need to remember to handle errors correctly.

Download progress

When we have to download a large amount of data, a way to follow the progress would be useful, especially when users have slow internet. Earlier, to implement progress indicators developers used XMLHttpRequest.onprogress callback. In .fetch() and axios, there are different ways to do it.

To track progress of download in .fetch() we can use one of the response.body properties, a ReadableStream object. It provides body data chunk by chunk, and it allows us to count how much data is consumed in time.

In axios, implementing a progress indicator is possible as well, and it’s even easier because there exists a ready module, which can be installed and implemented; it’s called Axios Progress Bar.

If you have a lot of large data to download and you want to track the progress in progress indicator, you can manage that easier and faster with axios but .fetch() gives the possibility as well, just it needs more code to be developed for the same result.

HTTP interception

HTTP interception can be important when we need to check or change our HTTP requests from the application to the server, or in the other way, for example, for authentication.

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

// request interceptor
axios.interceptors.request.use((config) => {
  console.log('Request sent');
})

// response interceptor
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 the request interception and response interception. In the first case, I created a console.log informing about sending requests, and in the response interception, we can do any action on response and then return it.

.fetch() doesn’t provide the HTTP interception by default, there’s a possibility to overwrite the .fetch() method and define what needs to happen during sending the request, but of course, it will take more code and can be more complicated than using axios functionality.

Conclusion

In this article, I compare two methods used for creating HTTP requests, starting for a simple overview, through syntax and some important features like download progress or error handling.

This comparison shows that Axios is a better solution in case of an application where there are a lot of HTTP requests which needs a good error handling or HTTP interceptions. In the case of small projects, with just a few simple API calls, Fetch can be a good solution as well.

It’s very important to pay attention to one more factor when choosing the best solution for your project. Axios is supported by most browsers and the Node.JS environment as well when Fetch is supported just by modern browsers and may have some issued with the older ones.

With this knowledge, I hope you are able to select the best solution for you, and you find this comparison helpful.

Duomly - Programming Online Courses

Thank you for reading,
Anna

#javascript #react #vue #axios #fetch #rest

Ben Taylor

Ben Taylor

1602646039

5 Ways To Make HTTP Requests In Node.js - 2020 Edition

Learning how to make HTTP requests can feel overwhelming as there are dozens of libraries available, with each solution claiming to be more efficient than the last. Some libraries offer cross-platform support, while others focus on bundle size or developer experience. In this post, we’ll explore five of the most popular ways to achieve this core functionality in Node.js.

The code demonstrations will use the Lord of the Rings themed API,  one API to rule them all, for all interactions-simply because I accidentally binge-watched the entirety of this excellent series last weekend.

Prerequisites

Ensure you have  npm and Node.js installed on your machine, and you’re good to go!

Prefer to jump ahead? This post will cover:

  • HTTP (The Standard Library)
  • SuperAgent
  • Axios
  • Node Fetch
  • Got

HTTP (The Standard Library)

The standard library comes equipped with the default http module. This module can be used to make an HTTP request without needing to add bulk with external packages. However, as the module is low-level, it isn’t the most developer-friendly. Additionally, you would need to use  asynchronous streams for chunking data as the async/await feature for HTTP requests can’t be used with this library. The response data would then need to be parsed manually.

#superagent #nodejs #http-request #axios #node-fetch

Fetch vs Axios: Which Is the Best Library for Making HTTP Requests?

Axios and Fetch provide a seemingly equal API and set of features, so which one is better for making HTTP requests?

This article aims to provide you with an overview of both tools so you can make a better-informed decision when picking a tool to send HTTP requests.

We’ll compare:

  • CRUD operations
  • Automatic JSON parsing
  • Interceptors
  • Error handling
  • Request timeout functioning

#axios #fetch #api #web-development