Guide to Axios js Http Client
Axios is an HTTP client, build for communication between the front-end and the back-end, also Axios js can be used on the server-side with Node.js. There are a couple of other ways to do the communication, the most common are Fetch API, jQuery Ajax and Axios. In the past jQuery's Ajax was the most used standard for communication, but developers are moving away from it in favor of native APIs, and if you use frameworks like React Axios is more or less used in most of the cases. In this article, we will look at Axios an HTTP based client.
What is Axios js
Axios is promise-based, same as the Fetch but it is much more powerful and flexible over the native Fetch API. Here are the major features of Axios:
Transform request and response
Intercept request and response
Make http requests from node js
Cancel requests
Automatic transforms for JSON data
Make XMLHttpRequests from the browser
Supports the Promise API
Client-side support for protecting against XSRF
Great for web frameworks like React, React Native, etc
How to Install Axios js
Axios js can be installed with couple of methods (Axios NPM, bower, yarn, cdn) let's see how to install Axios examples:
npm:
$ npm install axios
bower:
$ bower install axios
yarn:
$ yarn add axios
cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Requests
Making an HTTP request with Axios is very easy. In its basic form, the object must have a URL property; if there is no method provided, GET will be used by default as a value. Let’s look at a simple Axios request example:
// POST request
axios({
method: 'post',
url: '/signin',
data: {
firstName: 'John',
lastName: 'Smith'
}
});
Axios post example
In the example above we are simply telling the client to send a POST request to /login
with a data object of key-value pairs as its data. Axios will do the conversion of the data to JSON format and send it as the request body.
Also we have out of the box methods for performing different types of requests. Let's take a look at a couple of the provided methods.
axios.get
axios.post
axios.put
axios.patch
axios.delete
Let's modify the code of the previous example with the axios.post
method.
axios.post('/signin', {
firstName: 'John',
lastName: 'Smith'
});
Axios post example
We can also send custom headers with Axios. To send custom headers we simply need to pass an object with the headers as the last argument in the method.
const options = {
headers: {'X-Custom-Header': 'value'}
};
axios.post('/signin', {
firstName: 'John',
lastName: 'Smith'
}, options);
Axios post example with options
Responses
As Axios is a promise-based client once the HTTP request is made Axios will return a promise that is fulfilled or rejected. We will use the Async/Await JavaScript feature (if you are not familiar with the Async/Await you can read more about it at Async JavaScript Part 3: Async/Await to handle the response, but if you are not familiar with it you can use the then()
method.
signIn = async () => {
try{
let res = await axios.post("/signin", {
firstName: 'John',
lastName: 'Smith'
});
}catch(e){
//handle the error
}
};
Axios response example
If the promise is fulfilled we will get the response in the res
else if it is rejected we will get the error in our catch block. The fulfilled response object from the request contains the following information:
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
// All header names are lower cased
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 the browser
request: {}
}
Axios Response Schema (Source: npmjs)
Transform request and response
Axios automatically transforms request and responses to JSON, but in some cases, if we need to send formats like CSV or XML we can override the default behavior and define a different transformation. To change the request data before sending it to the server, we need to set the transformRequest
property in the config object (this method only works for POST, PUT, PATCH).
const options = {
method: 'post',
url: '/signin',
data: {
firstName: 'John',
lastName: 'Doe'
},
transformRequest: [(data, headers) => {
// transform the data
return data;
}]
};
// send the request
axios(options);
Intercept request and response
Intercept look similar to transform, but unlike transforms, which only receive the data and headers as arguments, interceptors receive the entire response object or request config and can change the HTTP request. You can make a request interceptor in Axios like in the next example.
// request interceptor
axios.interceptors.request.use(config => {
// perform a task before the request is sent
console.log('Request was sent');
return config;
}, error => {
// handle the error
return Promise.reject(error);
});
// send a get request
signIn = async () => {
try{
let res = await axios.get("/some_endpoint");
}catch(e){
//handle the error
}
};
Axios interceptors example
Here we are logging a message when a request is sent and we wait for a response from the server. With interceptors, it is no longer needed to implement tasks for each HTTP request. Response interceptor is also provided, which allows us to transform the responses.
// response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// send a get request
signIn = async () => {
try{
let res = await axios.get("/some_endpoint");
}catch(e){
//handle the error
}
};
Axios interceptors example
Cancel requests
Sometimes you may want to cancel a request that is already sent, Axios allows us to cancel a request by using a cancel token.
const source = axios.CancelToken.source();
somefunc = async () => {
try{
let res = await axios.get("/some_endpoint");
}catch(e){
if(axios.isCancel(thrown)) {
console.log(thrown.message);
}else{
//handle the error
}
}
};
// cancel the request (the message parameter is optional)
source.cancel('Request canceled.');
Axios cancel request example
Automatic transforms for JSON data
Axios automatically convert requests and responses to JSON, but in some cases, if we want to we can override the default transformation and define other data formats like CSV or XML. To change the default behavior of Axios we need to set the tranasformRequest
property in the config (This method only works for POST, PUT and PATCH requests). Let's check the next example of how to change the default transformation in Axios.
const options = {
method: 'post',
url: '/signin',
data: {
firstName: 'John',
lastName: 'Doe'
},
transformRequest: [(data, headers) => {
// transform the data
return data;
}]
};
// send the request
axios(options);
Axios transforms example
To transform the data before sending it, we can set a transformResponse
property in the config.
const options = {
method: 'post',
url: '/signin',
data: {
firstName: 'John',
lastName: 'Doe'
},
transformResponse: [(data) => {
// transform the response
return data;
}]
};
// send the request
axios(options);
Axios transforms example
Client-side support for protecting against XSRF
Axios offer good protection against XSRF (Cross-site request forgery) attacks by allowing you to add additional auth data when making requests. With this feature, the server can discover the requests that are coming from unauthorized locations. We can see how we can achieve this protection in the following example.
const options = {
method: 'post',
url: '/signin',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
};
// send the request
axios(options);
Axios protection against XSRF example
Browser support
Axios js has great browser support even for older browsers, you can check the browser support on the table below.
Chrome | Firefox | Safari | IE | Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | 11+ | Yes | Yes |
Conclusion
Axios is one of the most popular HTTP clients available out there, equipped with great useful features. Axios is also great with libraries like React and for doing HTTP calls from backend with Node js. In this tutorial, we have seen just the major features of Axios js with examples. If you are interested for more info about the client, you can check the official Axios Github Page, or Axios NPM page for more info and documentation.
Tweet