Published: October 03 2021

Axios vs Fetch - HTTP POST Request Comparison by Example

Below are examples of HTTP POST 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 POST request with a JSON body

This sends an HTTP POST request to the Reqres api which is a fake online REST api used for testing, it includes a generic /api/<resource> route that supports POST requests to any <resource> and responds with the contents of the post body and a dynamic id property. This example sends an article object to the /api/articles route and then writes the id from the response to the #post-request .article-id element so it's displayed on the page.

Axios POST request with a JSON body

// Simple POST request with a JSON body using axios
const element = document.querySelector('#post-request .axios .article-id');
const article = { title: 'Axios POST Request Example' };
axios.post('https://reqres.in/api/articles', article)
    .then(response => element.innerHTML = response.data.id);

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

Fetch POST request with a JSON body

// Simple POST request with a JSON body using fetch
const element = document.querySelector('#post-request .fetch .article-id');
const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
fetch('https://reqres.in/api/articles', requestOptions)
    .then(response => response.json())
    .then(data => element.innerHTML = data.id );

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


POST request with async/await - Axios vs Fetch

This sends the same POST 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 POST request with async/await

(async () => {
    // POST request using axios with async/await
    const element = document.querySelector('#post-request-async-await .axios .article-id');
    const article = { title: 'Axios POST Request Example' };
    const response = await axios.post('https://reqres.in/api/articles', article);
    element.innerHTML = response.data.id;
})();

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

Fetch POST request with async/await

(async () => {
    // POST request using fetch with async/await
    const element = document.querySelector('#post-request-async-await .fetch .article-id');
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'Fetch POST Request Example' })
    };
    const response = await fetch('https://reqres.in/api/articles', requestOptions);
    const data = await response.json();
    element.innerHTML = data.id;
})();

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


POST request with error handling - Axios vs Fetch

This sends a POST request to an invalid url on the api then writes the error message to the parent of the #post-request-error-handling .article-id element and logs the error to the console.

Axios POST request with error handling

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

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

Fetch POST 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.

// POST request using fetch with error handling
const element = document.querySelector('#post-request-error-handling .fetch .article-id');
const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
fetch('https://reqres.in/invalid-url', requestOptions)
    .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.id;
    })
    .catch(error => {
        element.parentElement.innerHTML = `Error: ${error}`;
        console.error('There was an error!', error);
    });

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


POST request with set HTTP headers - Axios vs Fetch

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

Axios POST request with set HTTP headers

// POST request using axios with set headers
const element = document.querySelector('#post-request-set-headers .axios .article-id');
const article = { title: 'Axios POST Request Example' };
const headers = { 
    'Authorization': 'Bearer my-token',
    'My-Custom-Header': 'foobar'
};
axios.post('https://reqres.in/api/articles', article, { headers })
    .then(response => element.innerHTML = response.data.id);

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

Fetch POST request with set HTTP headers

// POST request using fetch with set headers
const element = document.querySelector('#post-request-set-headers .fetch .article-id');
const requestOptions = {
    method: 'POST',
    headers: { 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my-token',
        'My-Custom-Header': 'foobar'
    },
    body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
fetch('https://reqres.in/api/articles', requestOptions)
    .then(response => response.json())
    .then(data => element.innerHTML = data.id);

Example Fetch POST request at https://stackblitz.com/edit/axios-vs-fetch-http-post-request-examples?file=post-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