React HTTP Requests: Axios vs Fetch

Jordan Panasewicz
4 min readJun 10, 2021

--

Every developer knows about fetch requests… Axios is essentially an NPM alternative to “fetching” data, with some cool additional features. With over 18 million weekly downloads, if you aren’t familiar with Axios, I definitely recommend checking it out!

So let’s take a quick look at some of the extra features Axios can offer:

  • Make XMLHttpRequests from the browser
  • Make http requests from Node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

First and foremost, one of my favorite things about Axios is the syntax. While it still has all the power behind custom configurations and fetching with options, it is overall a much cleaner feel.

To import Axios, run ‘npm i axios’ to install it, and then import (react) or require it (node) into your file:

react.js: import axios from "axios" 
node.js: const axios = require('axios');

Once we’re here, we can already make basic, or more customized http requests. A simple get request for a user with a certain ID can be handled in several ways, and I love the built in Error Handling with Axios as seen here as well:

Option 1: simple get request to user with query params for ID:

axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

Option 2: simple get request to get user with more customizable and organized params:

axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

Option 3: async functionality?!

async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}

Post, put, patch, and delete requests are just as simple and include error handling as well:

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

More Complex Scenarios

So far, while impressive, these examples have been fairly straight forward. What if we want to perform multiple concurrent requests?

No problem! Here we are using the Promise API to get a user account and that user’s permissions:

function getUserAccount() {
return axios.get('/user/12345');
}

function getUserPermissions() {
return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});

We can also use the Axios API to configure our http request in many ways. Here’s another basic example from the docs to post a user:

axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});

The documentation for Axios is fairly simple and straightforward.

The different request method aliases keep things clean and requires less flipping back and forth to documentation:

axios.request(config)axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.options(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])

You can also create an instance with a certain configuration with the basic syntax: “axios.create([config])”, and then use that configuration with any of the instance methods (similar layout to the request methods above).

For example:

const exampleInstanceConfig = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});

and then usage of instance methods for our exampleInstanceConfig:

axios#request(exampleInstanceConfig)axios#get(url[, exampleInstanceConfig])axios#delete(url[, exampleInstanceConfig])axios#head(url[, exampleInstanceConfig])axios#options(url[, exampleInstanceConfig])axios#post(url[, data[, exampleInstanceConfig]])axios#put(url[, data[, exampleInstanceConfig]])axios#patch(url[, data[, exampleInstanceConfig]])axios#getUri([exampleInstanceConfig])

The response schema is very helpful as well, providing the full data body, as well as some additional information from the request:

{
// `data` is the response that was provided by the server
data: {},

// `status` is the HTTP status code from the server response
status: 200,

// `statusText` is the HTTP status message from the server response
statusText: 'OK',

// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},

// `config` is the config that was provided to `axios` for the request
config: {},

// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}

On top of all these handy features, Axios also has the ability to utilize interceptors, create and provide request cancellation tokens, handle errors more elegantly, make requests in browser or in node, utilize promises more powerfully, and even includes typescript definitions.

Check out the docs here to get started and take advantage of Axios!

Cheers!

--

--

Jordan Panasewicz
Jordan Panasewicz

Written by Jordan Panasewicz

Denver, CO based. Software Sales turned Software Engineer.

No responses yet