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

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

相关推荐
wordbaby几秒前
TanStack Router 基于文件的路由
前端
wordbaby5 分钟前
TanStack Router 路由概念
前端
wordbaby7 分钟前
TanStack Router 路由匹配
前端
cc蒲公英8 分钟前
vue nextTick和setTimeout区别
前端·javascript·vue.js
程序员刘禹锡13 分钟前
Html中常用的块标签!!!12.16日
前端·html
我血条子呢23 分钟前
【CSS】类似渐变色弯曲border
前端·css
DanyHope24 分钟前
LeetCode 两数之和:从 O (n²) 到 O (n),空间换时间的经典实践
前端·javascript·算法·leetcode·职场和发展
hgz071025 分钟前
企业级多项目部署与Tomcat运维实战
前端·firefox
用户18878710698425 分钟前
基于vant3的搜索选择组件
前端
zhoumeina9925 分钟前
懒加载图片
前端·javascript·vue.js