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
Installing Axios
There are multiple ways to installing axios. here are some
Using npm:
Using bower:
Using Yarn:
Using CDN:
JsDelivr and unpkg both provide CDN scirpts for Axios
Now that we have installed the axios. Let us go towards a easy example on how to send requests
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:
Now creating 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
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
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
the complete code looks like
The POST Request can also be sent by passing the relevant config
to the axios
axios(config);
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
Thus we can send POST request using Axios with async and await
POST request with HTTP headers
Adding HTTP headers to our post Request is quite easy. Just add the headers to the config
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
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
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.
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
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.
This way we can send GET requests using the Async / Await keywords
Intercepting req and res
You can intercept requests or response befoer they are handled by then
or catch
Create a intereceptor like
and if you need to add a response interceptor then
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