Published: October 04 2021

Axios vs Fetch - HTTP GET Request Comparison by Example

This post shows examples of HTTP GET requests sent with axios side by side with the same requests sent with fetch so you can compare the two and decide which you prefer.

Other HTTP examples available:


What's the difference?

The Fetch API (fetch) is native so it comes bundled with all modern browsers, and Axios is available as a package on npm, both libraries do the same thing - send HTTP requests. Axios has a few extra features built in like progress events, request timeouts and interceptors, but these can also be implemented using fetch with a bit of extra code. The one you choose really depends on the project and preference of the team, if your code complexity and maintenance is reduced by using axios (because you use a lot of the built in features) then I think it's worth the cost of adding an extra dependency to your app, otherwise I'd lean towards fetch.


Installing axios from npm

With the npm CLI: npm install axios

With the yarn CLI: yarn add axios


Simple GET request - Axios vs Fetch

This sends an HTTP GET request to the Reqres api which is a fake online REST api used for testing, it includes an /api/users route that supports GET requests and returns an array of users plus the total number of users. This example writes the total from the response to the #get-request .total element so it's displayed on the page.

Axios GET request

// Simple GET request using axios
const element = document.querySelector('#get-request .axios .total');
axios.get('https://reqres.in/api/users')
    .then(response => element.innerHTML = response.data.total);

Example Axios GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request/axios.js

Fetch GET request

// Simple GET request using fetch
const element = document.querySelector('#get-request .fetch .total');
fetch('https://reqres.in/api/users')
    .then(response => response.json())
    .then(data => element.innerHTML = data.total );

Example Fetch GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request/fetch.js


GET request with async/await - Axios vs Fetch

This sends the same GET request, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

Axios GET request with async/await

(async () => {
    // GET request using axios with async/await
    const element = document.querySelector('#get-request-async-await .axios .total');
    const response = await axios.get('https://reqres.in/api/users');
    element.innerHTML = response.data.total;
})();

Example Axios GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request-async-await/axios.js

Fetch GET request with async/await

(async () => {
    // GET request using fetch with async/await
    const element = document.querySelector('#get-request-async-await .fetch .total');
    const response = await fetch('https://reqres.in/api/users');
    const data = await response.json();
    element.innerHTML = data.total;
})();

Example Fetch GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request-async-await/fetch.js


GET request with error handling - Axios vs Fetch

This sends a GET request to an invalid url on the api then writes the error message to the parent of the #get-request-error-handling .total element and logs the error to the console.

Axios GET request with error handling

// GET request using axios with error handling
const element = document.querySelector('#get-request-error-handling .axios .total');
axios.get('https://reqres.in/invalid-url')
    .then(response => element.innerHTML = response.data.total)
    .catch(error => {
        element.parentElement.innerHTML = `Error: ${error.message}`;
        console.error('There was an error!', error);
    });

Example Axios GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request-error-handling/axios.js

Fetch GET request with error handling

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block.

// GET request using fetch with error handling
const element = document.querySelector('#get-request-error-handling .fetch .total');
fetch('https://reqres.in/invalid-url')
    .then(async response => {
        const isJson = response.headers.get('content-type')?.includes('application/json');
        const data = isJson && await response.json();

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        element.innerHTML = data.total;
    })
    .catch(error => {
        element.parentElement.innerHTML = `Error: ${error}`;
        console.error('There was an error!', error);
    });

Example Fetch GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request-error-handling/fetch.js


GET request with set HTTP headers - Axios vs Fetch

This sends the same GET request again with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.

Axios GET request with set HTTP headers

// GET request using axios with set headers
const element = document.querySelector('#get-request-set-headers .axios .total');
const headers = {
    'Authorization': 'Bearer my-token',
    'My-Custom-Header': 'foobar'
};
axios.get('https://reqres.in/api/users', { headers })
    .then(response => element.innerHTML = response.data.total);

Example Axios GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request-set-headers/axios.js

Fetch GET request with set HTTP headers

// GET request using fetch with set headers
const element = document.querySelector('#get-request-set-headers .fetch .total');
const headers = {
    'Authorization': 'Bearer my-token',
    'My-Custom-Header': 'foobar'
};
fetch('https://reqres.in/api/users', { headers })
    .then(response => response.json())
    .then(data => element.innerHTML = data.total);

Example Fetch GET request at https://stackblitz.com/edit/axios-vs-fetch-http-get-request-examples?file=get-request-set-headers/fetch.js

 


Need Some HTTP Help?

Search fiverr for freelance HTTP developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by