Axios GET and POST examples
alakkadshaw
Posted on January 9, 2023
This article was originally published on the DeadSimpleChat Blog: Axios GET and POST examples
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 of 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
using bower
$ bower install axios
Using Yarn:
$ yarn add axios
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>
Now that we have installed the axios. Let us go towards a easy example on how to send requests
💡 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
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
Now creating a POST request
axios.post('/addCandy',{
candyName: 'Mars Bar',
quantity: '24'
});
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'
}
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)
})
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);
});
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);
});
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'
}
});
There are also alias methods that can be used as an alternative to the above methods
axios.post(url,[data[,config]])
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
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)
});
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);
});
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
}
})
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());
});
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
});
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
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);
}
}
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);
});
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);
});
If you need to remove the interceptor later on in the code
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
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
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
Posted on January 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.