Axios Vs fetch what should you use

Axios Vs fetch what should you use

One of the basic tasks of any web application is to speak with servers through the Hypertext Transfer Protocol (HTTP). This will be simply achieved with the use of Fetch or Axios. Fetch and Axios area unit terribly similar in the functions. Some developers like Axios over integral genus Apis for its easy use. The Fetch API is absolutely capable of reproducing the key options of Axios. Which is better?

Developers always claim since fetch is an inbuilt function and does not need an external library and for these reasons, this fetch is the best. Is fetch considered the right solution or Axios lets discuss

JSON

Using the fetch() method, users need to use some kind of method on the response data. When users are sending the body with the request, users need to stringify the data.

// fetch

fetch('url')
  .then((response) => response.json())
  .then((data) => console.log(data))
 
  .catch((error) => console.log(error));

with the response, we need to process the response.json() action.

JSON data in fetch(), there is a two-step process.

We need to make the actual request first then the second step calls the .json() method on the response.

In Axios we pass data in the request or get data from the response, and data is automatically stringified. Therefore, no other operations are required

axios.get('url')
    .then((response)=>console.log(response))
      .catch((error)=>console.log(error))

Automatic transformation of data is a nice feature to have in Axios.

Download progress

Progress indicators are very useful when loading large assets, especially for users with slow internet speed. Previously, JavaScript programmers used the XMLHttpRequest.onprogress callback handler to implement progress indicators.

The Fetch API doesn’t have an onprogress handler. Instead, it provides an instance of ReadableStream via the body property of the response object.

The following example illustrates the use of ReadableStream to provide users with immediate feedback during image download:

// original code: https://github.com/AnthumChris/fetch-progress-indicators

<div id="progress" src="">progress</div>
<img id="img">

<script>

'use strict'

const element = document.getElementById('progress');

fetch('https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg')
  .then(response => {

    if (!response.ok) {
      throw Error(response.status+' '+response.statusText)
    }

    // ensure ReadableStream is supported
    if (!response.body) {
      throw Error('ReadableStream not yet supported in this browser.')
    }

    // store the size of the entity-body, in bytes
    const contentLength = response.headers.get('content-length');

    // ensure contentLength is available
    if (!contentLength) {
      throw Error('Content-Length response header unavailable');
    }

    // parse the integer into a base-10 number
    const total = parseInt(contentLength, 10);

    let loaded = 0;

    return new Response(

      // create and return a readable stream
      new ReadableStream({
        start(controller) {
          const reader = response.body.getReader();

          read();
          function read() {
            reader.read().then(({done, value}) => {
              if (done) {
                controller.close();
                return; 
              }
              loaded += value.byteLength;
              progress({loaded, total})
              controller.enqueue(value);
              read();
            }).catch(error => {
              console.error(error);
              controller.error(error)                  
            })
          }
        }
      })
    );
  })
  .then(response => 
    // construct a blob from the data
    response.blob()
  )
  .then(data => {
    // insert the downloaded image into the page
    document.getElementById('img').src = URL.createObjectURL(data);
  })
  .catch(error => {
    console.error(error);
  })

function progress({loaded, total}) {
  element.innerHTML = Math.round(loaded/total*100)+'%';
}
</script>

Implementing a progress indicator in Axios is simpler, especially if you use the Axios Progress Bar module. First, you need to include the following style and script:

<link rel="stylesheet" type="text/css"  />

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

Then you can implement the progress bar like this:

<img id="img">

<script>

loadProgressBar();

const url = 'https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg';

function downloadFile(url) {
  axios.get(url, {responseType: 'blob'})
    .then(response => {
      const reader = new window.FileReader();
      reader.readAsDataURL(response.data); 
      reader.onload = () => {
        document.getElementById('img').setAttribute('src', reader.result);
      }
    })
    .catch(error => {
      console.log(error)
    });
}

downloadFile(url);

</script>

This code uses the FileReader API to asynchronously read the downloaded image. The readAsDataURL method returns the image’s data as a Base64-encoded string, which is then inserted into the src attribute of the img tag to display the image.

Response Timeout

Fetch

Fetch() provides the response timeout functionality through the AbortController interface.

const controller = new AbortController();
const signal = controller.signal;
const options = {
  method: 'POST',
  signal: signal,
  body: JSON.stringify({
    firstName: 'Muthu',
    lastName: 'B'
  })
};  
const promise = fetch('/login', options);
const timeoutId = setTimeout(() => controller.abort(), 5000);

promise
  .then(response => {/* handle the response */})
  .catch(error => console.error('timeout exceeded'));
  


In the above code, using the AbortController.AbortController() constructor, you need to create an AbortController object. The AbortController object allows you to later abort the request. If the server doesn’t respond in less than five seconds, the operation is terminated by calling controller.abort().

Axios

By using the optional timeout property in the config object, you can set the number of milliseconds before the request is terminated.

axios({
    method: 'post',
    url: '/login',
    timeout: 5000,    // 5 seconds timeout
    data: {
      firstName: 'Muthu',
      lastName: 'B'
    }
  })
  .then(response => {/* handle the response */})
  .
  .catch(error => console.error('timeout exceeded'))

Simultaneous requests

To make multiple simultaneous requests, Axios provides the axios.all() method. Simply pass an array of requests to this method, then use axios.spread() to assign the properties of the response array to separate variables:

axios.all([
  axios.get('https://api.github.com/users/muthuks2020'), 
  axios.get('https://api.github.com/users/facebook')
])
.then(axios.spread((obj1, obj2) => {
  // Both requests are now complete
  console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
  console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));

You can achieve the same result by using the built-in Promise.all() method. Pass all fetch requests as an array to Promise.all(). Next, handle the response by using an async function, like this:

Promise.all([
  fetch('https://api.github.com/users/muthuks2020'),
  fetch('https://api.github.com/users/facebook')
])
.then(async([res1, res2]) => {
  const a = await res1.json();
  const b = await res2.json();
  console.log(a.login + ' has ' + a.public_repos + ' public repos on GitHub');
  console.log(b.login + ' has ' + b.public_repos + ' public repos on GitHub');
})
.catch(error => {
  console.log(error);
});


No alt text provided for this image

Conclusion

For most of your HTTP communication needs, Axios provides an easy-to-use API in a compact package. There are some alternative libraries for HTTP communication, a tiny and elegant HTTP client based on window.fetch; superagent, a small, progressive client-side HTTP request library based on XMLHttpRequest. But Axios is a better solution for applications with a lot of HTTP requests and for those that need 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.


要查看或添加评论,请登录

Dr.MuthuKumaraswamy B的更多文章

  • AI Agents in Enterprise Production: Strategies for Success

    AI Agents in Enterprise Production: Strategies for Success

    AI and ML-driven agents are revolutionizing enterprise environments, but deploying them effectively in production…

  • Inside the Mind of an AI Agent: How It Works and Why It Matters

    Inside the Mind of an AI Agent: How It Works and Why It Matters

    Autonomous agents operate much like humans, relying on fundamental components such as identity, memory, planning, and…

  • Faster way to learn programming languages

    Faster way to learn programming languages

    Getting better at something faster isn't about skipping topics and being half-baked. I'm not showing you any shortcuts.

    3 条评论
  • Explaining AI: What Do Business Leaders Need to Care?

    Explaining AI: What Do Business Leaders Need to Care?

    AI and the challenge of model explainability. The use of artificial intelligence (AI) has become more widespread and is…

  • Vertex-AI

    Vertex-AI

    At the Google I/O developer conference earlier in May, Google Cloud announced the global launch of Vertex AI, a machine…

  • Multi-cloud redefined by Google

    Multi-cloud redefined by Google

    Ask anyone from the IT industry or anyone who observes the IT industry to name the top trends in the industry which…

    1 条评论
  • Async JS with Promises from Go

    Async JS with Promises from Go

    In JavaScript, Promise’s are the foundation of async/await. Lets take up an example, consider the below code, This will…

  • JavaScript Objects in Go and WebAssembly

    JavaScript Objects in Go and WebAssembly

    WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Implement your…

  • JavaScript Design Patterns

    JavaScript Design Patterns

    A pattern describes a Challange that happens over and another time in the environment, so describes the core of the…

  • Top 4 Reasons to adopt JAMstack

    Top 4 Reasons to adopt JAMstack

    JAM stands for JavaScript, APIs, and markup. Primarily you build the principles for the generator in JavaScript, use…

社区洞察

其他会员也浏览了