Back to all posts

Fetch API vs Axios : a tools for making HTTP requests


Choosing Between Them:

  • For simple requests in modern browsers, Fetch can be sufficient.
  • For projects requiring more features, convenience, or wider browser support, Axios is a better choice.

Using Axios:

So if i want to use Axios, how can I install them

// Using npm:
$ npm install axios

Using Axios:

async function fetchDataWithAxios() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
    console.log(response.data); // Log the fetched data (post object)
  } catch (error) {
    console.error("Error:", error);
  }
}

fetchDataWithAxios();

Using Fetch API:

async function fetchDataWithFetch() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error(`Error fetching data: ${response.status}`);
    }
    const data = await response.json();
    console.log(data); // Log the fetched data (post object)
  } catch (error) {
    console.error("Error:", error);
  }
}

fetchDataWithFetch();

Both examples achieve the same goal of fetching data from a public API endpoint. However, Axios offers a cleaner syntax with built-in error handling and automatic data parsing