DEV Community

Cover image for Fetch vs Axios in Javascript
Suman Roy
Suman Roy

Posted on • Updated on

Fetch vs Axios in Javascript

Hello there ! 👋 In this blog, we are going to learn how to implement APIs by using Fetch API and Axios

Before we get started, the only pre-requisite needed for this tutorial is basic understanding of javascript.

Table of contents

  1. What is fetch?
  2. Syntax of fetch
  3. What is axios?
  4. Syntax for axios
  5. Key differences b/w fetch and axios

What is Fetch ?

Fetch is a standard way of sending asynchronous api calls to the server in web applications. It is a feature of ECMASCRIPT6(ES6) and was introduced back in 2015.
The Fetch API provides a method called fetch () which is defined on the window object. It needs an argument which is the url of the endpoint (resource). This method returns a promise which is resolved to retrieve the response.

Let us see an example, where we are fetching some data from an endpoint

const fetchNames = ()=>{
   fetch("https://localhost:5000/api/names/")
      .then((res)=> res.json()) // successful req, change to json
      .then((data)=>{
       console.log(data); // data contains the json object
    })
     .catch(error=>{
       console.log(error); // something went wrong
    })
}
Enter fullscreen mode Exit fullscreen mode

Note that, for Post request we also need to include the options
For example, we are sending a name with id to the server

const sendName=()=>{
    fetch("http://localhost:5000/api/user/", {
       // the method type 
       method : 'POST',
       // contents to send i.e., the body
       body: JSON.stringify({
        name : 'David',
        id:"1"
       }),
       // headers of the request
       headers:{
        'Content-type':'Application/json'  
       }
      })
      .then( res => res.json())
      .then( data=> console.log(data))
      .catch(error => console.log(error))
}
Enter fullscreen mode Exit fullscreen mode

So, we know how fetch works. Now, let us see axios.

What is Axios?

Axios is a javascript library used to make HTTP requests from node js(runtime for javascript) or XMLHttpRequests (XHR) from the browser. This too supports the promise api that is native to ES6.

Example for showing how we can fetch data and post data using axios

 // get request
  const fetchNames = async()=>{
   // we are using asynchronous function so we need to await for 
   the req to be processed
   try{
     const response = await 
     axios.get('http://localhost:5000/api/names/');
     console.log(response.data)
   }catch(error){
      console.log(error);
  }
}

// post request
const postName = async()=>{
   // same as previous
   try{
      const response = await 
       axios.post('http://localhost:5000/api/users/',{
          name:'David',
          id:1
     });
     // log the data from the response 
      console.log(response.data);
   }catch(error){
     console.log(error); // something went wrong!
     }
}
Enter fullscreen mode Exit fullscreen mode

Key differences between fetch and axios

Fetch Axios
Fetch is built-in for most modern web browsers, so no installation is required Axios is a stand-alone third party package (library) which requires installation
Fetch has no url in the request object Axios has url in it's request object
It doesn't have XSRF (cross-site request forgery) protection It has XSRF protection in-built
Request is made then the response is converted to json Here, the response is automatically transformed to json
Request has body which is converted to string Request has data which contains the object itself
Abort requests by using Abort controller web api Has request-timeouts for cancelling requests or use AbortController

Hopefully, I have been able to clear the methods of making api calls to the server. If you have understood, then like the post, comment and share so that others can benefit from this.
Thank you for reading this far! Keep developing ! ❤❤

Top comments (10)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Quick note: fetch() can be aborted.

const abortC = new AbortController();
var responsePromise = fetch('http://longrunningrequest.example.com', { signal: abortC.signal });
setTimeout(() => abortC.abort(), 1000);
Enter fullscreen mode Exit fullscreen mode

If running in the browser developer tools, Network tab, you'll see that the request's status goes from (pénding) to (canceled).

Collapse
 
suman373_30 profile image
Suman Roy • Edited

Thanks for the update ! Have changed it 😀

Collapse
 
gadingnst profile image
Gading Nasution

Axios can be aborted using AbortController too 😅

Collapse
 
johnnycricket profile image
John Vorwald

Is there any other resources that look at adding a XSRF layer to fetch?

Collapse
 
suman373_30 profile image
Suman Roy

cheatsheetseries.owasp.org/cheatsh...

U might find it useful

Collapse
 
johnnycricket profile image
John Vorwald

Thanks!

Collapse
 
itsroy69 profile image
Jyotirmoy Roy

Well written

Collapse
 
suman373_30 profile image
Suman Roy

Thank you @itsroy69 🙏

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Nice comparaisons, how did you find this?

Collapse
 
suman373_30 profile image
Suman Roy

Resources from the internet.

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more