Complete Guide to Axios NPM Package

axios-http-client

Axios is an HTTP client, build for communication between the front-end and the back-end, also Axios 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 most used, but developers are moving away from it in favor of native APIs. In this article, we will look at Axios an HTTP based client.

Into Axios

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

Cancel requests

Automatic transforms for JSON data

Make XMLHttpRequests from the browser

Supports the Promise API

Client-side support for protecting against XSRF

Installation

Axios can be installed with the methods listed below:

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: 'Doe'
  }
});

In the example above we are simply telling the Axios 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. Axios provides us 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: 'Doe'
});

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: 'Doe'
  }, 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: 'Doe'
    });
  }catch(e){
    //handle the error
  }
};

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
  }
};

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. Axios also provides a response interceptor, 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
  }
};

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.');

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);

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);

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);

Browser support

Axios has great browser support even for older browsers, you can check the browser support on the table below.

ChromeFirefoxSafariEdgeIEOpera
SupportedSupportedSupportedSupported11+Supported

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. We have seen just the major features of Axios in this article. You can check the official Axios Github Page, or Axios NPM for more info and documentation.




#axios #http #javascript #npm

Author: Aleksandar Vasilevski |