Axios GET and POST examples
Axios GET and POST examples

Axios GET and POST examples

Dead Simple Chat Team

Table of Contents

Dead Simple Chat offers prebuilt Chat that can be added in minutes to any app or website. Can be completely customized and offers powerful Chat API and SDK.

In this article we are going to learn about how to send get and post requests with Axios. Axios is a promise based HTTP client for the browser and node.js server.

Axios can run the same code in the browser as well as on the server.

On the NodeJs server side it uses the  http module and on the browser side it uses XMLHttpRequests

We are going to learn more about axios below along with detailed examples on how to send and receive http requests for POST and GET

đź’ˇ
New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App —without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance  Sign Up for Free

Installing Axios

There are multiple ways to installing axios. here are some

Using npm:

$ npm install axios
installing axios using npm

Using bower:

$ bower install axios
installing axios using bower

Using Yarn:

$ yarn add axios
installing axios using Yarn

Using CDN:

JsDelivr and unpkg both provide CDN scirpts for Axios

//using JsDelivr
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
// using unpkg CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
using cdn

Now that we have installed the axios. Let us go towards a easy example on how to send requests

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

Making POST Request with Axios with JSON

Now let us create a POST request with Axios and there send the JSON data along with it

first let us require axios in our project like:

const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings
require axios in our project

Now creating a POST request

axios.post('/addCandy',{
    candyName: 'Mars Bar',
    quantity: '24'
});
making a post request

What are we doing were

We are using the axios.post to make a POST request on the path /addCandy and along with the POST request we are sending the JSON data

{
    candyName: 'Mars Bar',
    quantity: '24'
}
JSON data

When the server that receives this post request will save this data in its database and send a response back that all is ok with a response code of 200 or it will send a response that some error has occurred along with corresponding response code and error message

We need to record what message and code the server has sent we will be doing that next

axios.post('/addCandy',{
    candyName: 'Mars Bar',
    quantity: '24'
}).then(function(response){
    console.log(response)
})
making a post request 2

Also, it might happen that we are making a mistake in making the request and an error is happening on our side.

We need to catch that error as well. Let's add another line of code to catch that error as well

  .catch(function (error) {
    console.log(error);
  });
catch functionality

the complete code looks like

axios.post('/addCandy',{
    candyName: 'Mars Bar',
    quantity: '24'
}).then(function(response){
    console.log(response)
})
.catch(function (error) {
    console.log(error);
  });
axios post request

The POST Request can also be sent by passing the relevant config to the axios

axios(config);
//sending a post request
axios({
  method: 'post',
  url: '/addCandy',
  data: {
    candyName: 'Mars Bar',
    quantity: '24'
  }
});
axios API

There are also alias methods that can be used as an alternative to the above methods

axios.post(url,[data[,config]])
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

Making POST Request with Axios using Async/Await

A cleaner and simpler way of making POST request with Axios is by using the async await keywords

 import axios from 'axios';
const candyData = async()=> {
	const response = await axios.post('/addCandy',{
            candyName: 'Mars Bar',
            quantity: '24'
        })
    }
async await POST Axios

Thus we can send POST request using Axios with async and await

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

POST request with HTTP headers

Adding HTTP headers to our post Request is quite easy. Just add the headers to the config

//sending a post request
axios({
  method: 'post',
  url: '/addCandy',
  data: {
    candyName: 'Mars Bar',
    quantity: '24'
  },
  headers: {'X-Custom-Header': 'foobar'}
}).then(function(response){
	console.log(response)
});
sending headers with POST Request
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

Error Handling with POST and Get Request

It is quite easy to handle error requests with Axios. Here is an example of how you can handle error requests with Axios

//sending a post request
axios({
    method: 'post',
    url: '/addCandy',
    data: {
      candyName: 'Mars Bar',
      quantity: '24'
    }
  }).catch(function (error) {
    if(error.response){
        // the request was made and the server responded with the response code that is out of 2xx
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
    } else if (error.request) {
        // the request was made but no response was recieved the `error.request` is an instance of XMLHttpRequest in the browser and a instance of http.ClientRequet in Node.Js
        console.log(error.request);
    }else {
        // Something happened that triggered an error
        console.log('error', error.message);
    }
    console.log('err',error.config);
  });
  
handling error while sending POST requests

What are we doing here

We are sending a POST request using Axios and catching the error of it occurs

If the  error has response code out of the 2xx success code then we are logging the data, response code and the http headers that are returned by the server to better understand why the error occurred

If there is some problem with the request that we are sending then we are logging that to the console

If there is no problem with the request or the response and there is some other error that is occurring than we are also logging that to the console

In the end if there is something wrong with the config then we are logging that to the console

ValidateStatus config option

Using the validateStatus config option, we can define the HTTP codes that should throw an error. like for example

axios.get('/get-candies', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})
Error Handling using validateStatus

Using toJSON

If you need more information about the HTTP error code you can convert the error code to JSON using the toJSON function.

That would give you more information regarding the error.

axios.get('/get-candies')
  .catch(function (error) {
    console.log(error.toJSON());
  });
using toJSON
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

Making GET Request with Axios with JSON

First let us add the Axios to our project

const axios = require('axios').default;

and let us make the GET request

// Make a request for candies
axios.get('/get-candies')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
Get Request using Axios

We are making a GET request to the url '/get-candies' to get a list of candies from the server. Then we are logging the response that we get from the server on to the console.

The server might give us the data in the form of a list of candies along with the 2xx response code or the server might give us an error

If the server gives us an error we are logging that error on to the console

Now, we might want to add params to our request like for example

// Make a request forcandies from a brand name
axios.get('/get-candies?brand="mars"')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Now, we have added a params like ?parameterName=value

We can also make the GET request using the alternative method

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

This method is the similar to the previous method only thing being we have changed the config a bit for readability and it is easier this way to pass multiple parameters while sending the requests

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

Making GET Request with Axios using Async/Await

It is also very easy to make requests using async / await keywords. Keep in mind though older browsers like IE do not support the async keyword.

var candies = async function getCandies() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
GET request using Async / Await and Axios

This way we can send GET requests using the Async / Await keywords

đź’ˇ
New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App —without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance  Sign Up for Free

Intercepting req and res

You can intercept requests or response befoer they are handled by then or catch

Create a intereceptor like

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
adding interceptor

and if you need to add a response interceptor then

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });
response interceptor

If you need to remove the interceptor later on in the code

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
đź’ˇ
New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App —without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance  Sign Up for Free

Response Schema

The response schema of a request is as follows. You can use the response schema to log information that is relevant to you

{
  // Response provided by the server is data
  data: {},

  // HTTP code sent by the server is status
  status: 200,

  // `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: {}
}

You can log the information that is relevant to you like

axios.get('/candies')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

How to cancel requests

You can cancel Axios requests using the AbortController

const controller = new AbortController();

axios.get('/candies', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

A note the cancelToken API has been depricated since the version v0.22.0 and no longer works in the newer versions

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

URL encoding instead of JSON

By default the Axios serializes the body object in JSON but if you wish to send the request in application/x-www-form-urlencoded then you can do so using the below options

In the Browser

const params = new URLSearchParams()

params.append('param1', 'value1');
params.append('param2', 'value2');

axios.post('/send-candy',params);

Note the URLSearchParams is not supported by all browsers

In Node.JS

using the querystring module you can send the requests for example

const querystring = require('querystring');
axios.post('https://candies.com/', querystring.stringify({ candy: 'mars bar' }));

Conclusion

In this article I explained with examples how to send POST and GET requests with Axios