最强vue3+Ts axios封装!

最强vue3+Ts axios封装!_第1张图片

建立以上文件夹。随后将下面代码进行复制粘贴使用。

config.ts

/** webpack自带的
 * 开发环境:development
 * 生产环境:production
 * 测试环境:test
 */
let BASE_URL = "";
const TIME_OUT = 10000;
if (process.env.NODE_ENV === "development") {
  BASE_URL = "http://123.207.32.32:8000/";
} else if (process.env.NODE_ENV == "production") {
  BASE_URL = "http://codewhy.org/prod";
} else {
  BASE_URL = "http://coderwhy.org/test";
}

export {BASE_URL, TIME_OUT};

 type.js

import type {AxiosRequestConfig} from "axios";
//拦截器
export interface HYRequestInterceptors {
  requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig;
  requestInterceptorCatch?: (error: any) => any;
  responseInterceptor?: (res: any) => any;
  rrequestInterceptorCatch?: (error: any) => any;
}

export interface HYRequestConfig extends AxiosRequestConfig {
  interceptors?: HYRequestInterceptors;
  showLoading?: boolean;
}

request/index.ts

import axios from "axios";
import type {AxiosInstance} from "axios";
import type {HYRequestInterceptors, HYRequestConfig} from "./type";
import {ElLoading} from "element-plus";
import {ILoadingInstance} from "element-plus/lib/components/loading/src/loading.type";
const DEAFULT_LOADING = true;

class HYRequest {
  instance: AxiosInstance; //axios实例
  interceptors?: HYRequestInterceptors;
  showLoading: boolean;
  loading?: ILoadingInstance; //loading实例
  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    this.showLoading = config.showLoading ?? DEAFULT_LOADING;
    //单个实例的拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    //添加所有实例的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log("所有实例的拦拦截器:请求拦截成功");
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "正在请求数据...",
            background: "regba(0,0,0,0.5)"
          });
        }
        return config;
      },
      (err) => {
        console.log("所有实例的拦拦截器:请求拦截失败");
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        console.log("所有实例的拦拦截器:响应拦截成功");
        //将loading移除
        this.loading?.close();
        const data = res.data as any;
        if (data.returnCode === "-1001") {
          console.log("请求失败,错误信息");
        } else {
          return data;
        }
      },
      (err) => {
        console.log("所有实例的拦拦截器:响应拦截失败");
        if (err.response.status === 404) {
          console.log("404的错误");
        }
        return err;
      }
    );
  }
  //单个请求多拦截
  request(config: HYRequestConfig): Promise {
    return new Promise((resolve, reject) => {
      //判断单个请求是否有拦截
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }
      if (config.showLoading === false) {
        this.showLoading = config.showLoading;
      }
      this.instance
        .request(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }
          this.showLoading = DEAFULT_LOADING;
          //将结果res返回出去
          resolve(res);
        })
        .catch((err) => {
          this.showLoading = DEAFULT_LOADING;
          reject(err);
          return err;
        });
    });
  }

  get(config: HYRequestConfig): Promise {
    return this.request({...config, method: "get"});
  }

  post(config: HYRequestConfig): Promise {
    return this.request({...config, method: "post"});
  }

  delete(config: HYRequestConfig): Promise {
    return this.request({...config, method: "delete"});
  }

  patch(config: HYRequestConfig): Promise {
    return this.request({...config, method: "patch"});
  }
}

export default HYRequest;

index.ts

import HYRequest from "./request";
import {BASE_URL, TIME_OUT} from "./request/config";
const hyRequest = new HYRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      //携带token拦截
      const token = "";
      if (token) {
        const configs = config.headers as any;
        configs.Authorization = `Bearer${token}`;
      }
      console.log("请求成功的拦截");
      return config;
    },
    requestInterceptorCatch: (err) => {
      console.log("请求失败的拦截");
      return err;
    },
    responseInterceptor: (res) => {
      console.log("响应成功的拦截");
      return res;
    },
    rrequestInterceptorCatch: (err) => {
      console.log("响应失败的拦截");
      return err;
    }
  }
});

export default hyRequest;

main.ts

import {createApp} from "vue";
import App from "./App.vue";
import router from "./router";
import {ElButton} from "element-plus/lib/";
import http from "./service/index";
import "element-plus/theme-chalk/index.css";
import store from "./store";
createApp(App)
  .component(ElButton.name, ElButton)
  .use(store)
  .use(router)
  .mount("#app");

  interface DataType {
    data: any;
    returnCode: string;
    success: boolean;
  }

// http.request({
//   url: "/home/multidata",
//   method: "get",
//   interceptors: {
//     requestInterceptor: (config) => {
//       return config;
//     },
//     responseInterceptor: (res) => {
//       return res;
//     }
//   },
//   showLoading: true 显示loading 就加
// });



http
  .request({
    url: "/home/multidata",
    method: "get",
    showLoading: false
  })
  .then((res) => {
    console.log(res.data);
    console.log(res.returnCode);
    console.log(res.success);
  });

http
  .get({
    url: "/home/multidata",
    showLoading: false
  })
  .then((res) => {
    console.log(res.data);
    console.log(res.returnCode);
    console.log(res.success);
  });

你可能感兴趣的:(typescript,javascript,visual,studio)