Axios 101
Axios 101
Mar 8, 2021 12:45 PM (2 years ago)

# Axios 101

In a series of articles, we will learn what axios (opens new window) is, why does it exist and how can we use it in our projects.

# What the heck is it?

Making HTTP requests to fetch or save data is one of the most common tasks a client-side JavaScript application will need to do.
Axios is a Javascript library that is used to make HTTP requests from node.js or XHR (opens new window) from the browser that supports the ES6 Promise API (opens new window)

# Why does it exists?

Working in web development is interesting and many times quite challenging.
Sometimes, we are tasked with integrating our application with external services or fetching data from the server. Communications in such cases happens by sending HTTP requests.
Almost every website these days does this in some fashion.

# How to use it?

Now that we've understood the what and why of axios, let's get our feet wet and learn how to use it.

You can install axios using a number of ways based on your project setup:

// 1.Package managers such as npm, yarn etc.
npm install axios

// 2.Loading script tag to your html page from a Content delievery network
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Now that we've installed the library, using it quite easy.

The examples will assume that you have installed the library using the package manager (npm, yarn, etc..) option.

import axios from "axios";

// performing GET request
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
  });

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

// performing multiple concurrent requests
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];
});

# Configuration for Humans

Axios comes with it basic defaults but there are many times that we would be required to customize it to match our use case.
As you might have guessed it, the defaults that will be applied to every requests can be tweaked and customized. Here's how to do it

let config = {
  baseURL: "http://my-website.com/",
  responseType: "json"
  responseEncoding: "utf8",
  withCredentials: true,
  retries: 2,
  timeout: 1000, // A timeout in milliseconds to abort a request.
  xsrfCookieName: "XSRF-TOKEN",
  xsrfHeaderName: "X-XSRF-TOKEN",
  maxContentLength: -1,
  maxBodyLength: -1,
  headers: {
    // Accept: 'application/vnd.api+json',
    // 'Content-Type': 'application/vnd.api+json',
    // 'X-Requested-With': 'XMLHttpRequest',
  },
};

Another great feature of axios is Interceptors.
This allows you to hook into / intercept the request or response of the HTTP call, on the fly, opening a window of endless possiblities.

In simple words:

  • It allows you to write or execute a piece of your code before the request gets sent.
  • It allows you to write or execute a piece of your code before response reaches the calling end.

Examples of interceptors use cases:

  • Transform the request / response body
  • Handling Access & Refresh Tokens
  • Polling long running api calls

// based on the config we defined previously
let config {
    ...
    }

const httpClient = axis.create(confg);


// Request interceptor
httpClient.interceptors.request.use(function(request) {
    // do something before the request is sent

    return request
}, function(error) {
    // do something in case an error occured

    return Promise.reject(error)
});


// Response interceptor
httpClient.interceptors.response.use(function(response) {
  // Do something with response data

  return response
}, function(error) {
  // Do something with response error

   return Promise.reject(error);
})

# Conclusion

This concludes our introduction to axios, a promised-based HTTP library. The next article will be a deep dive to explore its configurations and see how it's been used in some of the open source projects.

See ya soon 👋

Muhidin Photo

Hello! I'm a full-stack web developer currently working for Ecobiz. In this publication, I share my journey as a software engineer. You can find me on Twitter and Github.