Performing HTTP Requests: Axios vs Fetch

Performing HTTP Requests: Axios vs Fetch

Any modern web app or website is difficult to imagine without servers and to create those connections between the clients and servers we use HTTP methods and web sockets.

In this article, we will be focusing on Axios and Fetch which are part of HTTP methods. So let us start by answering...

What is HTTP ??

Hypertext Transfer Protocol (HTTP) is a method for encrypting information and transporting it from client to server. In other words, it is one of the techniques used to send information securely from client to server.

Various HTTP Methods:

  • GET: used to request data from a specified resource.

  • POST: used to send data to a server to create/update a resource.

  • PUT: used to send data to a server to create/update a resource.

  • HEAD: almost identical to GET, but without the response body.

  • DELETE: The DELETE method deletes the specified resource.

  • PATCH: The PATCH request method applies partial modifications to a resource.

  • OPTIONS: OPTIONS method describes the communication options for the target resource.

There is a never-ending debate about REST VS GRAPHQL. REST is the easiest way to transfer data using endpoints. Graphql is a modern query language to query information and it is organized with schema and type system.

Firstly, let us know about various terms used in HTTP methods

Various Terms of HTTP Methods:

  • URL: The URL to access.

  • Headers: Represents response/request headers, allowing you to query them and take different actions depending on the results.

  • Request: Represents a resource request.

  • Response: Represents the response to a request. -Status: The result of the Request in numeric form.

What is Axios ??

Axios is a popular promise-based HTTP client which an easy-to-use of API that can use both in client and server.

Installation

To install the Axios Package

$ npm install axios or yarn add axios

The simple way to import Axios into the project

const axios=require("axios")

or with ES6

import axios from 'axios'
  • Making a GET Request with Axios
// The url for the request
const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/query"
// Fetching the Details using axios.get()
axios.get(`${API_ENDPOINT_FOR_REQUEST}`)
    .then((res)=>{
         console.log(res)}

     .catch((err) =>{
          console.log(err)}
  • Making the POST Request with Axios
// The url for posting the request.
const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/post"
axios.post(`${API_ENDPOINT_FOR_REQUEST}`, body,{
   headers:{token}})
 .then((res)=>{
         console.log(res)}

     .catch((err) =>{
          console.log(err)}
  • Making the PUT Request with Axios
const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/put"
axios.put(`${API_ENDPOINT_FOR_REQUEST}`, body,{
   headers:{
          token}})
 .then((res)=>{
         console.log(res)}

     .catch((err) =>{
          console.log(err)}
  • Making the DELETE Request using Axios
const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/delete"
axios.delete(`${API_ENDPOINT_FOR_REQUEST}`,{
  headers:{
         token}})
 .then((res)=>{
         console.log(res)}

     .catch((err) =>{
          console.log(err)}

What is fetch?

Fetch has been the most popular method to make HTTP requests in previous years, it is supported by almost all modern browsers and is also a Browser API. Vanilla Js uses the Fetch method to make HTTP Requests!

Installation

Fetch has built-in support in modern browsers, so you need not install or import it.

Syntax:

let promise = fetch(url, [options])

Begin with Fetch:

  • To make a GET request

      const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/get"
      fetch(`${API_ENDPOINT_FOR_REQUEST}`,{
           method: 'GET'
       }).then(response=>{
           return response.json()
       }).catch(err=>console.log(err))
    
  • To make a POST request

      const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/post"
      fetch(`${API}`,{
           method:'POST',
           headers:{
               Accept: 'application/json',
               Content-Type:'application/json'
           },
           body: JSON.stringify(user)
       })
           .then(response=>{
               return response.json()
       })
           .catch(err=>console.log(err))
    
  • To make a PUT Request

const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/put"
fetch(`${API_ENDPOINT_FOR_REQUEST}`,{
        method:'PUT',
        headers:{
            Accept: 'application/json',
           Content-Type:'application/json'
        },
        body: blog
    })
        .then(response=>{
            return response.json()
    })
        .catch(err=>console.log(err))
  • To make a DELETE request
const API_ENDPOINT_FOR_REQUEST = "http://localhost:2000/delete"
fetch(`${removeBlogEndPoint}`,{
        method:'DELETE',
        headers:{
            Accept: 'application/json',
            Content-Type:'application/json'
        },
    })
        .then(response=>{
            return response.json()
    })
        .catch(err=>console.log(err))

We have already seen a lot about Axios and fetch and how they work. Now let us discuss Axios vs Fetch

AXIOSFETCH
Axios has a URL in the request object.Fetch has no URL in the request object.
Axios is a stand-alone third-party package that can be easily installed.Fetch is built into most modern browsers, no installation is required as such.
Axios uses the data property.Fetch uses the body property.
Axios’ data contains the object.Fetch’s body has to be stringified.
Axios performs automatic transforms of JSON data.Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the .json() method on the response.
Axios allows canceling requests and requests timeout.Fetch does not allow canceling requests and request timeout.
Axios can intercept HTTP requests.Fetch, by default, doesn’t provide a way to intercept requests.
Axios cannot be used for caching Data in PWA(Progressive Web Apps)Fetch can be used for caching Data in PWA(Progressive Web Apps)

How to Choose Between Axios or Fetch ??

Using Fetch can be a little difficult when compared to Axios because of the little extra lines of code, but you will never regret the decision as it is flexible and widely recommended for modern apps and websites.

Whereas Go with the Axios if your beginner, it is easy to use and will not add any extra burden. Axios can even be used in Node.js to make certain API requests.

To know more about Axios and Fetch click on the links below

And That's a Wrap, Thanks for Reading!!!

If enjoyed reading this article. Do Like, Comment down your views, and share this article with your friends. Follow me for more such articles.