Fetch VS Axios | Make Https Requests like a pro.

Fetch VS Axios

A Modern Web App or Website is hard to image without a server and to establish a connection between Server and Client, here is where the concept of HTTP Requests, Web Sockets arises!

You can also follow me on GitHub mayHemant on Github

Various HTTPS 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 has been a never-ending debate since the HTTP Methods came into existence related to the use of Rest Vs GraphQl.

Rest(Representational state transfer): A short hint about rest is REST is the easiest way to Transfer data and also unknown as uncontrolled Fetch.

GraphQL: GraphQL is the modern Query Langauge used by well-known companies like Facebook and etc.. Which is also known as the Controlled Fetch.

We will dig deep into Rest and Graphql in our upcoming blogs, now let us move to Fetch vs Axios

Well know JavaScript HTTP Requests Libraries for 2020

  • AXIOS
  • Fetch
  • Superagent
  • Request
  • Supertest

Term's used in HTTP requests:

  • 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 that sports an easy-to-use API and can be used in both the browser and Node.js.

Installation

You will initially need to have Node Js Installed on your System, and that's it navigates to your client-side folder and follow up the command.

npm install axios or yarn add axios

Begin with Axios:

simply you can import Axios in your project with

const axios = require('axios')

or with ES6

import axios from 'axios'

Making a GET request with Axios

const Your_API_ENDPOINT_TO_REQUEST = "http://example:5050/query"
axios.get(`${Your_API_ENDPOINT_TO_REQUEST}`)
    .then((res)=>{
         console.log(res)}

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

Axios has been the easiest way to communicate between server and client.

  • To make a POST request
    const Your_API_ENDPOINT_TO_REQUEST = "http://example:5050/query"
    axios.post(`${Your_API_ENDPOINT_TO_REQUEST}`, body,{
       headers:{
              token}})
    // further you can handle the promise in the same manner
    
  • To make a PUT request

    const Your_API_ENDPOINT_TO_REQUEST = 
    "http://example:5050/query"
    axios.put(`${Your_API_ENDPOINT_TO_REQUEST}`, body,{
       headers:{
              token}})
    // further you can handle the promise in the same manner
    
  • To make a DELETE request

    const Your_API_ENDPOINT_TO_REQUEST = 
    "http://example:5050/query"
    axios.delete(`${Your_API_ENDPOINT_TO_REQUEST}`,{
      headers:{
             token}})
    // further you can handle the promise in the same manner
    

Making HTTP requests with Axios is a less load and a pretty understandable manner like reading a simple English book, also a good point here is you don't need to data.json() like Fetch.

What is fetch?

Fetch have been the most popular method to make Http request in previous years, it is supported by almost all the 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 to install or import it.

Syntax

let promise = fetch(url, [options])

Begin with Fetch:

  • To make a GET request

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

    const Your_API_ENDPOINT_TO_REQUEST = 
    "http://example:5050/query"
    fetch(`${API}/pre-signup`,{
         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

fetch(`${updateBlogEndPoint}`,{
        method:'PUT',
        headers:{
            Accept: 'application/json',
            Authorization: `Bearer ${token}`
        },
        body: blog
    })
        .then(response=>{
            handleResponse(response)
            return response.json()
    })
        .catch(err=>console.log(err))
  • To make a DELETE request
fetch(`${removeBlogEndPoint}`,{
        method:'DELETE',
        headers:{
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`
        },
    })
        .then(response=>{
            handleResponse(response)
            return response.json()
    })
        .catch(err=>console.log(err))

Using fetch feels like writing pure old skool js with parsing the response and etc..

We have seen a lot about Axios and Fetch and also learned about the methods to make requests, let now talk about AXIOS vs FETCH.

  • While performing caching in PWA using a service worker you won't be able to cache if you are using Axios API (it works only with fetch API).

  • Fetch's body has to be stringified, Axios' data contains the object.

  • Fetch has no URL in the request object, Axios has a URL in the request object.

  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'.

  • Fetch usually runs the then and catch both blocks, which would let you see the full status of the request which would be unnecessary at some phase, but Axios just return the error block, which is more or what easy to read and debug!

  • Fetch is by default a browser API, and some talks have been around with importing Axios and making your dependencies heavy.

  • Fetch is the Javascript method where Axios is an add of dependency.

  • You can customize your response according to your need something like data.response.custom.whatever.part which is not a part in Axios!

How to Choose Between Axios or Fetch?

Using fetch can be a 7-8 lines extra code but you will never regret using it, as it is flexible a browser API and is widely supported like Axios!

If you are a Beginners go with AXIOS, don't add an extra burden on your shoulders, and you are well known for promises and JS objects and wanted to stick with JS Use fetch.

I mainly use Fetch in most of my projects!

References

  • Wikipedia
  • StackOverFlow

You can follow me on Twitter: MayHemant

Thank You for reading this and hope you liked the post, and if you have any suggestions please make sure to comment on them below.

In case of issue or help feel free to reach me out on twitter🐦

Manish⚡Nayak's photo

Amazingly curated!🕊️ I don't know much about these things, but loved reading it. Your words made to read it all, prettily mentioned everything in brief ❤️ Keep Writing, boy! One day, you will reach the maximum height of success🌻 Untill next time, Manish🌿

Hemant Joshi's photo

Thank you so much Manish, you are really awesome.

Max's photo

Axios is awesome, you dont have to parse data.

Hemant Joshi's photo

Thanks, good luck.

Hemant Joshi's photo

Hii, Everyone looking to hear whats your favorite one. Also Really Thankful for the read.

Khasti Devi Joshi's photo

Awesome.

Also read about Swr from Vercel, which is awesome with caching etc.

Hemant Joshi's photo

Thanks, i have heard about it and will surely use it

Steezy's photo

I don't agree completely, cause you can cache requests from Axios too, by converting into string and setting back to browser cache.

Hemant Joshi's photo

Would agree, also i read about vercel/swr which is really awesome

Dhia Bela's photo

Really awesome, just saw it on twitter.

Keep the good work up

Hemant Joshi's photo

wow, thanks a lot

Andrew Baisden's photo

Sooo good you compared them well.

Hemant Joshi's photo

Glad you liked. Thanks.

Kingsley Ubah's photo

This is a brilliant piece, welldone!

Hemant Joshi's photo

Thanks a lot man!

stegmann's photo

Lol, I get stuck with error handling in Axios, it isn't promise-based.

I love fetch

Hemant Joshi's photo

yup, try-catch is only way

Avnni's photo

Axios any day.

Hemant Joshi's photo

Axios is also awesome, but the one I hate is the error handling.

Harshad's photo

haha, you made me pro but don't mind I use graphql

Hemant Joshi's photo

lol, useQuery please

Mayank Joshi's photo

Awesome post Hemant.

Hemant Joshi's photo

Thanks a lot man.