Introduction

One of the fundamental tasks of a frontend application is to communicate with servers through the HTTP protocol. JavaScript can send network requests to the server and load new information whenever needed without reloading the page.

The term for that kind of operation is Asynchronous JavaScript And XML (AJAX), which uses the XMLHttpRequest object to communicate with the servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.

In this guide, we will be looking at how to make a network request to get information from the server asynchronously with the fetch() API and Axios and learn how they can be used to perform different operations.

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.

The fetch() 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.

The code below demonstrates a very basic fetch request in which we are fetching a JSON file across the network.

fetch('examples/example.json')
  .then((response) => {
    // Do stuff with the response
  })
  .catch((error) => {
    console.log('Looks like there was a problem: \n', error);
  });

The second argument that the fetch() method takes is the request object.

{
  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 the body contents
  • response.bodyUsed: Stores a Boolean that declares whether the body has been used in a response yet
  • response.headers: The headers object associated with the response
  • response.ok: A Boolean indicating whether the response was successful or not
  • response.redirected: Indicates whether or not the response is the result of a redirect
  • response.status: The status code of the response
  • response.statusText: The status message corresponding to the status code
  • response.type: The type of the response
  • response.url: The URL of the response

There are a number of methods available to define the body content in various formats:

  • response.json(): Parse the response as JSON
  • response.text(): Read the response and return as text
  • response.formData(): Return the response as FormData object
  • response.blob(): Return the response as Blob
  • response.arrayBuffer(): Return the response as ArrayBuffer

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 intercept http requests and responses.
  • It automatically transform request and response data.
  • It enables client-side protection against XSRF.
  • It has built-in support for download progress.
  • It has the ability to cancel requests.

Axios does not come as a native JavaScript API, so we will have to manually import into our project. To get started, we will have to include the following commands:

  • Using cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • Using npm
npm install axios
  • Using bower
bower install axios

And make a request as follows:

axios.get('examples/example.json')
  .then((response) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  })

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

You can check out the comprehensive request config in the official documentation.

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
  • response.statusText: HTTP status message from the server response
  • 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

We’re now familiar with the definitions and usage of axios and fetch(). Let’s focus our attention on how to perform some real world operations with both Axios and Fetch.

#axios #javascript #programming #developer

Axios vs. Fetch?
6.35 GEEK