Axios tutorial: How to Make HTTP Requests(GET/POST) with Axios

Axios is a “promise-based HTTP client that works in the browser and a Node.js environment”. It allows you to request a given endpoint, such as an external API or your own backend server.

Axios has lots of advantages over the native Fetch API:

  1. It supports older browsers (Fetch needs a polyfill)
  2. It has a way to abort a request.
  3. It has a way to set a response timeout.
  4. It has built-in CSRF protection.
  5. It supports upload progress.
  6. It performs automatic JSON data transformation.
  7. It works with Node.js very well.

Axios HTTP Client

Axios HTTP Client is the “Promise-based HTTP client for the browser and Node.js”. Axios HTTP Client will teach you how to use Axios POST request to the server or Axios GET request to fetch the data. It supports all modern browsers, including support for IE8 and higher.

It is promise-based, letting us write async/await code to perform XHR requests very quickly.

First, create one folder called axios-prac by the following command.

mkdir axios-prac

cd axios-prac

Now, we need to create the package.json file. So let us build using the following command.

npm init -y

Getting Started With Axios Promise Based HTTP Client Tutorial Example

Step 1: Install Axios HTTP Library.

Install an Axios HTTP client library. We can install it using the npm or yarn.

npm install axios --save

# Or

yarn add axios

# Or a content delivery network:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios POST Tutorial Example

Step 2: Create the server.js file.

Inside the root folder, create one file called server.js.

We send an Axios GET request to the GitHub API and fetch the data. So let us add the following code inside the server.js file.

const axios = require('axios');

async function getGithubData() {
  let res = await axios.get('https://api.github.com/users/KrunalLathiya');
  console.log(res.data.login);
}

getGithubData();

Here, also we have used the async-await feature of ES7. Save the file, go to the terminal or CMD, and type the following command to run the node server.

node server

You can see that my name has been printed, which means we have successfully sent an HTTP Request using Axios.

So, this is how anyone can use Axios with Node.js. It is effortless. It is the primary example of Axios API. So, let us dive into Axios and get more details.

Axios API

You can start an HTTP request from the axios object.

axios({
  url: 'https://api.github.com/users/KrunalLathiya',
  method: 'get'
})

But generally, we do not use the above syntax. Instead, we can use the following syntax.

axios.get()
axios.post()

Axios offers methods for all the HTTP verbs which are less popular but still used:

  1. axios.put()
  2. axios.delete()
  3. axios.patch()
  4. axios.options()
  5. axios.head()

Axios GET

 Axios GET is the method to make HTTP GET requests using the Axios library. An HTTP GET request is used to send a request for a specified resource from a server.

const axios = require('axios');

function getGithubData() {
  axios.get('https://api.github.com/users/KrunalLathiya')
    .then(res => {
       console.log(res.data.login);
    });
  }

getGithubData();

We will get the same result, but we have used a promise to resolve the request and get the data.

If the promise does not resolve, it will be rejected, and we can get an error in the catch block.

const axios = require('axios');

function getGithubData() {
  axios.get('https://api.github.com/users/KrunalLathiya')
    .then(res => {
      console.log(res.data.login);
    })
    .catch(err => {
      console.log(err);
    });
 }

getGithubData();

We can also pass the parameter to the Axios GET Request. The syntax for that is the following.

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

Axios POST

Performing the Axios POST request is just like making a GET request, but instead of axios.get(), you can use axios.post() function. You can pass the payload as a second argument.

axios.post('https://appdividend.com', {
  foo: 'bar'
})

Axios Request Config/Options

We can write the following code inside the JavaScript file to set up the global config.

axios.defaults.headers.post['header1'] = 'value' // for POST requests
axios.defaults.headers.common['header1'] = 'value' // for all requests

We can send an Axios GET request with the Authorization Token.

axios.get('https://appdividend.com', {
  headers: {
    Authorization: 'Bearer ' + token //the token is a variable which holds the token
  }
});

We can add the config object like the following code if we work with the POST request.

let config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  responseType: 'blob'
};

axios.post('https://appdividend.com', data, config)
  .then((response) => {
    console.log(response.data);
});

So, here we have passed the three parameters in the Axios Post Request.

  1. URL (Where we need to send an HTTP request).
  2. Data (That needs to be posted and saved in the database).
  3. Request object.

So, you can pass the following options in the request.

  • baseUrl: if you specify a base URL, it’ll be prepended to any relative URL you use.
  • headers: It is an object of key-value pairs to be sent as headers.
  • params: an object of key/value pairs that will be serialized and appended to the URL as a query string.
  • responseType: if we want to get the response in a format other than JSON, we can set this property to arraybufferblobdocumenttext, or stream.
  • auth: Auth option is used when we need to pass an object with the username and password credentials for HTTP Basic authentication on the request.

Axios Response Object

When the HTTP request is successfully sent, then () callback will receive a response object with the following properties:

  • data: the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you.
  • status: the HTTP code returned from the server.
  • statusText: the HTTP status message returned by the server.
  • headers: all the headers sent back by the server.
  • config: the original request configuration.
  • request: the actual XMLHttpRequest object (when running in a browser).

Axios error object

If there is any problem with the axios request, the promise will be rejected with an error object containing the following properties:

  • message: the error message text.
  • response: the response object (if received), as described in the previous section.
  • request: the actual XMLHttpRequest object (when running in a browser).
  • config: the original request configuration.

Axios Interceptors

We can intercept the request or response sometimes, like sending a request or receiving the response object. Axios also allows us to add functions called interceptors. Like transforms, these interceptor functions can be attached to fire when a request is made or when a response is received.

axios.interceptors.request.use((config) => {
 // Do something before request is sent
 return config;
 }, (error) => {
 // Do something with request error
 return Promise.reject(error);
 });

// Add a response interceptor
axios.interceptors.response.use((response) => {
 // Do something with response data
 return response;
 }, (error) => {
 // Do something with response error
 return Promise.reject(error);
 });

Multiple Axios requests simultaneously.

To execute multiple requests in parallel, provide an array argument to axios.all(). Then, when all requests are complete, you’ll receive an array containing the response objects in the same order they were sent.

Alternatively, you can use axios spread to spread the array into multiple arguments.

The spread is preferred since dealing with array indexes could be misleading.

axios.all([
  axios.get('https://api.github.com/users/codeheaven-io');
  axios.get('https://api.github.com/users/codeheaven-io/repos')
 ])
 .then(axios.spread(function (userResponse, reposResponse) {
  //... but this callback will be executed only when both requests are complete.
  console.log('User', userResponse.data);
  console.log('Repositories', reposResponse.data);
 }));

Third-party Add-ons

Axios can benefit from an ecosystem of third-party libraries that extend its functionality. From interceptors to testing adaptors to loggers, a variety is available. Here are a few that I think you may find helpful:

  • axios-mock-adaptor: It allows you to easily mock requests to facilitate code testing.
  • axios-cache-plugin: It is a wrapper for selectively caching GET requests.
  • redux-axios-middleware: If you’re a Redux user, this middleware provides a neat way to dispatch Ajax requests with open old actions.

Thanks for taking it.

5 thoughts on “Axios tutorial: How to Make HTTP Requests(GET/POST) with Axios”

  1. Hi Krunal,

    Thanks a lot for a lucid article.

    Can you please share an example of how to use the custom timeout with the axios.

    Reply
  2. Great article!
    I found the axios.all function to be useful.
    Minor edit: the list of ‘axios.get’ requests in the in axios.all should be comma* separated.

    Reply
    • do we have a way to get partial response from server? when server sends multiple flushes using the response writer. looking for something like a progress tracking.

      Reply
  3. Hi Krunal
    Thanks for creating this.

    I have a question regarding installing axios.

    Please let me know how to correct these errors
    I am in Step 1 of your page i.e installing axios

    1. If I use npm I get the following error:
    `– axios@0.21.1
    `– follow-redirects@1.13.2

    npm WARN axios-prac@1.0.0 No description
    npm WARN axios-prac@1.0.0 No repository field.
    2. if I use yarn I get the following error
    yarn add axios
    ERROR: [Errno 2] No such file or directory: ‘add’

    Please let me know how to correct these errors.

    Thanks in advance
    Vishwa

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.