03_Axios工具方法的封装

前言

前面为项目添加了规范工具,下面就要正式进入代码环节了。不过在这之前需要先对一些内容进行封装,这篇文章先记录下Axios的封装,主要包含以下内容:

  • axios的基本封装
  • 全局loading效果
  • mockjs的基本使用

Axios

先说这是什么,Axios是基于Promise的现代化客户端,用于发送HTTP请求的库。它可以在浏览器和Node环境中发送HTTP请求,这个我想各位都熟悉,毕竟谁的简历没有过掌握Vue全家桶这句话....。

跑题了跑题了,先说基本封装

安装

npm i axios

封装

tsx 复制代码
import Axios from 'axios';
import ReactDOM from 'react-dom/client';
import SpinCom from '@/components/ui/Spin';

//记录loading的状态
let loadingInstance = false;
//记录有loading的请求数量
let needLoadingRequestCount = 0;
Axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';
Axios.defaults.baseURL = '/';

// 要展示的loading
function showLoading() {
  loadingInstance = true;
  const dom = document.createElement('div');
  dom.setAttribute('id', 'loading');
  dom.style.zIndex = '1000';
  document.body.appendChild(dom);
  ReactDOM.createRoot(dom).render(<SpinCom />);
}

// 请求结束清理loading
function removeLoading() {
  if (needLoadingRequestCount === 0) {
    loadingInstance = false;
    if (document.getElementById('loading')) {
      document.body.removeChild(
        document.getElementById('loading') as HTMLElement,
      );
    }
  }
}

//请求拦截
Axios.interceptors.request.use(
  (config) => {
    if (config?.loading) {
      if (needLoadingRequestCount === 0) {
        //创建loading效果
        showLoading();
      }
      //计数
      needLoadingRequestCount++;
    }
    // 这里可以对请求携带的数据进行处理,不过我没加 哈哈哈哈
    return config;
  },
  function (error) {
    loadingInstance && removeLoading();
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);
//响应拦截
Axios.interceptors.response.use(
  (response) => {
    if (response.config?.loading) {
      needLoadingRequestCount--;
      //判断needLoadingRequestCount的数值
      needLoadingRequestCount =
        needLoadingRequestCount < 0 ? 0 : needLoadingRequestCount;
      //计数等于0并且有值则关闭loading
      needLoadingRequestCount === 0 && loadingInstance && removeLoading();
    }

    // 这里可以对后端返回的结果进行处理
    // 比如后端返回的错误信息、状态码等等 都可以在这里进行处理之后
    // 再将你想返回的数据return回去
    return response.data;
  },
  function (error) {
    if (loadingInstance) {
      needLoadingRequestCount--;
      needLoadingRequestCount =
        needLoadingRequestCount < 0 ? 0 : needLoadingRequestCount;
      needLoadingRequestCount === 0 && loadingInstance && removeLoading(); //关闭加载动画
    }
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  },
);

export default Axios;

下面还有一些内容,在 Axios.interceptors.request.use中可以看到config.loading,不过这个不是Axios自带的。如果在js中使用,这样写是没有问题的。但是在tsx中编辑器会提示错误。

所以我们需要 创建一个 axios.d.ts文件,添加以下代码

ts 复制代码
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import * as axios from 'axios';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { AxiosRequestConfig } from 'axios';

declare module 'axios' {
  //解决自定义loading参数ts报错的问题
  export interface AxiosRequestConfig {
    loading?: boolean;
    // [自定义属性声明]
  }
  //解决axios返回promise参数不对等的问题
  interface AxiosInstance {
    (config: AxiosRequestConfig): Promise<request<any>>;
  }
}

使用

ts 复制代码
import Axios from '@/utils/request';

export interface request<T> {
  code: number;
  msg: string;
  result: T;
}

export function handleUserLogin(data: UserLoginType) {
  return Axios({
    url: '/login',
    method: 'POST',
    data: data,
    loading: true,
  });
}


//另一个文件
handleUserLogin(data).then((res:request<any>)=>{
    //业务逻辑
})

Mockjs

当你没有后端服务的时候,可以使用Mockjs来伪造一些数据。它会劫持对应的HTTP请求,使用它可以帮你正常走流程,你只需要找后端要过来接口的数据格式就ok了。具体配置请看 MackJS官网

安装

npm install mockjs @types/mockjs -d

使用

ts 复制代码
import Mock from 'mockjs';

Mock.setup({
  timeout: 1000,
});

Mock.mock('/login', function () {
  return Mock.mock({
    code: 200,
    msg: '',
    result: {
      token: '123456789',
      userName: 'admin',
      password: '123456789',
    },
  });
});

然后在react的main.tsx中引入这个文件就可以了

main.tsx 复制代码
import '@/utils/mock/index';

好了,就这些,完活!!!有什么不对的地方欢迎评论探讨。。。

相关推荐
itslife5 分钟前
提交 Fiber 树
前端·react.js
一个专注api接口开发的小白9 分钟前
亚马逊 API 实战:商品详情页实时数据采集接口开发与调用
前端·数据挖掘·api
再吃一根胡萝卜14 分钟前
简单了解react-monaco-editor
前端
独立开阀者_FwtCoder15 分钟前
Nginx 部署负载均衡服务全解析
前端·javascript·后端
哒哒哒52852042 分钟前
HTTP缓存
前端·面试
T___44 分钟前
从入门到放弃?带你重新认识 Headless UI
前端·设计模式
wordbaby1 小时前
React Router 中调用 Actions 的三种方式详解
前端·react.js
黄丽萍1 小时前
前端Vue3项目代码开发规范
前端
curdcv_po1 小时前
🏄公司报销,培养我成一名 WebGL 工程师⛵️
前端
Jolyne_1 小时前
前端常用的树处理方法总结
前端·算法·面试