I Love ReactJS

Encapsulating axios in React applications

introduction to Axios

Axios is a promise-based HTTP library that can be used in browsers and node.js.

Features

install

  1. yarn installation
$ yarn add axios
  1. npm installation
npm install axios -D

3.bower installation

$ bower install axios

easy to use

aixos can be loaded directly through cdn, for example:

<html>
<head>
<title>The use of Axios</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
</head>
<body>
   <input type="button" onclick="getList()" value="Click get"/>
   <div id="content"> </div>

   <script type="text/javascript">

      function getList(){
             axios.request({
                 url:'/article/home/index',
                 method:'get',
                 baseURL:'http://test.mediastack.cn/'

            }).then(
               res => {
                 console.log("get res:",res);
                 var str=JSON.stringify(res);
                 document.getElementById("content").innerHTML = str;

              },error => {
                 console.log("get request failed:",error);
                 document.getElementById("content").innerHTML = error;
              }
            );
      }
   
   </script>
</body>
</html>

axios is encapsulated in react

Axios can be encapsulated into a file in

react. Through control operations, unified handling of errors, logic, and validation can be achieved, reducing the redundancy and readability of the code.

request encapsulation

/ * *
* Network request configuration
, /
import axios from "axios";

axios.defaults.timeout = 100000;
axios.defaults.baseURL = "http://test.mediastack.cn/";

/ * *
* http request interceptor
, /
axios.interceptors.request.use(
  (config) => {
    config.data = JSON.stringify(config.data);
    config.headers = {
      "Content-Type": "application/json",
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/ * *
* http response interceptor
, /
axios.interceptors.response.use(
  (response) => {
    if (response.data.errCode === 2) {
      console.log("out of date");
    }
    return response;
  },
  (error) => {
    console.log("request error:", error);
  }
);

/ * *
* encapsulate the get method
*@paramUrl request url
*@paramParams request parameters
*@returns {Promise}
 */
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
        params: params,
      }).then((response) => {
        landing(url, params, response.data);
        resolve(response.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

/ * *
* encapsulate the post request
*@param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data) {
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(
      (response) => {
        / / close the progress bar
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/ * *
* encapsulate the patch request
*@param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        msag(err);
        reject(err);
      }
    );
  });
}

/ * *
* encapsulate the put request
*@param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        msag(err);
        reject(err);
      }
    );
  });
}

/ / Unified API processing, returning data
export default function (fecth, url, param) {
  let _data = "";
  return new Promise((resolve, reject) => {
    switch (fecth) {
      case "get":
        console.log("begin a get request,and url:", url);
        get(url, param)
          .then(function (response) {
            resolve(response);
          })
          .catch(function (error) {
            console.log("get request GET failed.", error);
            reject(error);
          });
        break;
      case "post":
        post(url, param)
          .then(function (response) {
            resolve(response);
          })
          .catch(function (error) {
            console.log("get request POST failed.", error);
            reject(error);
          });
        break;
      default:
        break;
    }
  });
}

/ / failure prompt
function msag(err) {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        alert(err.response.data.error.details);
        break;
      case 401:
        alert("unauthorized, please log in");
        break;

      case 403:
        alert("access denied");
        break;

      case 404:
        alert("request address error");
        break;

      case 408:
        alert("request timeout");
        break;

      case 500:
        alert("Server internal error");
        break;

      case 501:
        alert("Service not implemented");
        break;

      case 502:
        alert("Gateway error");
        break;

      case 503:
        alert("Service is not available");
        break;

      case 504:
        alert("Gateway timeout");
        break;

      case 505:
        alert("HTTP version is not supported");
        break;
      default:
    }
  }
}

/ * *
* View the returned data
*@param url
 * @param params
 * @param data
 */
function landing(url, params, data) {
  if (data.code === -1) {
  }
}

as above, you can add common request headers, token verification and other operations by intercepting axios requests.

request quarantine

import http from '../utils/http';



/ * *
* get the list of home page
, /
function getArticleList(){
  return new Promise((resolve, reject) => {
    http("get",'/article/home/index').then(res => {
      resolve (res);
    },error => {
      console.log("Network exception ~",error);
      reject(error)
    })
  }) 
}

export {
   getArticleList
}

the react component calls as follows:

import React, { Component } from "react";
import { getArticleList } from "~/api/blog";

class Home extends Component {
    constructor(props) {
        super(props);
    } 

    componentDidMount() {
       getArticleList().then(
          (res) => {
              console.log("get article response:", res);
          },
         (error) => {
              console.log("get response failed!");
          }
       );
    }

 ......
}


export default Home;

in this way, we can try our best to make the data request so that the page logic does not interfere with each other, and it is also convenient for unified maintenance and modification in the later period.

Exit mobile version