Axios

From Expertiza_Wiki
Jump to navigation Jump to search

How Modern UI frameworks like React fetch data from server

Almost all of the new UI frameworks such as ReactJS, Angular or Vue use JavaScript templates with JSX, TypeScript or HTML which compile to Single Page Applications. This means once the base 'index.html' page is loaded into the client's browser, no further web page requests are made again to the server. In order to fetch data dynamically as required in reactive manner, asynchronous HTTP requests (AJAX calls) are made, using the RESTful protocol with Get, Post, Delete and Patch methods. These AJAX calls transact in commonly accepted formats like JSON or XML. Once the new data is fetched and available on the client side, the UI frameworks change the components on the web page to display the new data, keeping the web page same. This reduces load on the servers, improves computing performance with CDN caching and eliminates heavy payload responses containing redundant HTML.

Why Axios with React

ReactJS is a frontend library which has a primary function of rendering elements on the DOM effectively. In order to trim the size and keep the focus on core functionality, ReactJS does not ship with an in-built HTTP client like JQuery. Instead it provides us with a framework to create Components, which can be extended and integrated with third party tools to add more functionality. For example, Redux is a commonly used tool along with React for better State Management. Likewise, Axios is one of the most widely and un-opinionated tool used with React for making HTTP requests. More about it can be found on this link

Axios can be easily integrated into any UI framework and its extensible nature and simplicity make it one of the most popular tools used to make HTTP calls following the RESTful protocol. It states clear status messages like 200, 401, 404 etc for all requests and takes care of packing & unpacking of payload responses and its parameters while making HTTP calls. The 'data' field in an Axios response specifies the response payload which is a JSON object that can be easily converted into a JavaScript object in browser and makes the data handling efficient.

Furthermore, Axios supports the Promise API which is the standard way of handling asynchronous methods or callbacks in JavaScript as defined by the EcmaScript committee. Based on the response received from server, the Promise is either 'resolved' or 'rejected' if the status code is not 200 OK. The 'catch' and 'then' blocks of Promise API make it easier to selectively wait and make next asynchronous HTTP calls without blocking the client UI.

We will use Axios to make requests to our Expertiza backend which will transact with JSON data, and based on the responses we receive, appropriate Components and routes will be displayed to the user in the browser. The best part about this is, by keeping the backend same, we can also extend it to create a Mobile App for Expertiza based on JSON REST service.

Introduction

Axios is a Promise-based HTTP client prominently used in conjunction with frontend libraries like React or Vue. Its main function is to make asynchronous HTTP requests to the REST service providers, using the typical request-response pattern usually in JSON format. It supports the Promise API which ensures proper handling of the asynchronous requests.

Installation

Axios can be simply installed locally (in the node_modules of your project) as a NPM package using the command npm install axios or it can also be installed globally (in the system node_modules cache) using the command npm install -g axios

Usage

Performing a GET AJAX request

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

An example from our React front end making HTTP Post call to authenticate a user.

export const forgetPasswordUpdate = (email, password, repassword, token) => {
   // console.log(email, password, repassword, token)
   return dispatch => {
       axios({
           method: 'post',
           url: 'password_retrieval/forgottenPasswordUpdatePassword',
           headers: { "Content-Type": "application/json"},
           data:{ "token": token, "reset": { "email": email, "password": password, "repassword": repassword }}
       })
       .then(response => {
           console.log(response)
           // alert('A password reset link has been sent to the address on file for this account.')
           dispatch(actions.passwordResetSuccess())
       })
       .catch(error => {
               console.log(error)
               alert('password reset failed')
               dispatch(actions.passwordResetFailure())
              } )
   }

}