ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

最强vue3+Ts axios封装!

2021-10-13 16:01:46  阅读:1156  来源: 互联网

标签:axios console log res interceptors Ts vue3 return config


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

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<T>(config: HYRequestConfig): Promise<T> {
    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<any, any>(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<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({...config, method: "get"});
  }

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

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

  patch<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({...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<DataType>({
    url: "/home/multidata",
    method: "get",
    showLoading: false
  })
  .then((res) => {
    console.log(res.data);
    console.log(res.returnCode);
    console.log(res.success);
  });

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

标签:axios,console,log,res,interceptors,Ts,vue3,return,config
来源: https://blog.csdn.net/qq_46927610/article/details/120745457

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有