当前位置:   article > 正文

[Typescript]简易封装Axios_axios 封装typesciprt

axios 封装typesciprt

[Typescript]简易封装Axios

注意:axios版本:1.4

MyRequest:基于Axios封装的对象

import axios from "axios";
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
// 定义一个常见后端请求返回
type BaseApiResponse<T> = {
  code: number;
  message: string;
  result: T;
};
// 拓展 axios 请求配置,加入我们自己的配置
interface RequestOptions {
  // 是否全局展示请求 错误信息
  globalErrorMessage?: boolean;
  // 是否全局展示请求 成功信息
  globalSuccessMessage?: boolean;
}
// 拓展自定义请求配置
interface ExpandAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
  interceptorHooks?: InterceptorHooks;
  requestOptions?: RequestOptions;
}
// 拓展 axios 请求配置
interface ExpandInternalAxiosRequestConfig<D = any>
  extends InternalAxiosRequestConfig<D> {
  interceptorHooks?: InterceptorHooks;
  requestOptions?: RequestOptions;
}
// 拓展 axios 返回配置
export interface ExpandAxiosResponse<T = any, D = any>
  extends AxiosResponse<T, D> {
  config: ExpandInternalAxiosRequestConfig<D>;
}
export interface InterceptorHooks {
  requestInterceptor?: (
    config: InternalAxiosRequestConfig
  ) => InternalAxiosRequestConfig;
  requestInterceptorCatch?: (error: any) => any;
  responseInterceptor?: (
    response: AxiosResponse
  ) => AxiosResponse | Promise<AxiosResponse>;
  responseInterceptorCatch?: (error: any) => any;
}
// 导出Request类,可以用来自定义传递配置来创建实例
export default class MyRequest {
  // axios 实例
  private _instance: AxiosInstance;
  // 默认配置
  private _defaultConfig: ExpandAxiosRequestConfig = {
    baseURL: "",
    timeout: 5000,
    requestOptions: {
      globalErrorMessage: true,
      globalSuccessMessage: false,
    },
  };
  private _interceptorHooks?: InterceptorHooks;
  constructor(config: ExpandAxiosRequestConfig) {
    // 使用axios.create创建axios实例
    this._instance = axios.create(Object.assign(this._defaultConfig, config));
    this._interceptorHooks = config.interceptorHooks;
    this.setupInterceptors();
  }
  // 通用拦截,在初始化时就进行注册和运行,对基础属性进行处理
  private setupInterceptors() {
    this._instance.interceptors.request.use(
      this._interceptorHooks?.requestInterceptor,
      this._interceptorHooks?.requestInterceptorCatch
    );
    this._instance.interceptors.response.use(
      this._interceptorHooks?.responseInterceptor,
      this._interceptorHooks?.responseInterceptorCatch
    );
  }
  // 定义核心请求
  public request(config: ExpandAxiosRequestConfig): Promise<AxiosResponse> {
    return this._instance.request(config);
  }
  public get<T = any>(
    url: string,
    config?: ExpandAxiosRequestConfig
  ): Promise<AxiosResponse<BaseApiResponse<T> | any>> {
    return this._instance.get(url, config);
  }
  public post<T = any>(
    url: string,
    data?: any,
    config?: ExpandAxiosRequestConfig
  ): Promise<T> {
    return this._instance.post(url, data, config);
  }
  public put<T = any>(
    url: string,
    data?: any,
    config?: ExpandAxiosRequestConfig
  ): Promise<T> {
    return this._instance.put(url, data, config);
  }
  public delete<T = any>(
    url: string,
    config?: ExpandAxiosRequestConfig
  ): Promise<T> {
    return this._instance.delete(url, config);
  }

  public postXForm<T = any>(url: string, data?: any): Promise<T> {
    return this._instance.post(url, data, {
      // 利用 transformRequest 进行转换配置
      transformRequest: [
        function (oldData) {
          let newStr = "";
          for (let item in oldData) {
            newStr +=
              encodeURIComponent(item) +
              "=" +
              encodeURIComponent(oldData[item]) +
              "&";
          }
          newStr = newStr.slice(0, -1);
          return newStr;
        },
      ],
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132

实例化并导出

先实例化一个MyRequest对象,export出去使用

import MyRequest, { InterceptorHooks, ExpandAxiosResponse } from "./axios";

// 请求拦截器
const transform: InterceptorHooks = {
  requestInterceptor(config) {
    // 请求头部处理,如添加 token
    const token = localStorage.getItem("accessToken");
    if (token) {
      config!.headers!.Authorization = token;
    }
    return config;
  },
  requestInterceptorCatch(err) {
    // 请求错误,这里可以用全局提示框进行提示
    return Promise.reject(err);
  },


  // 请求拦截
  responseInterceptor(result) {
    // 因为 axios 返回不支持扩展自定义配置,需要自己断言一下
    const res = result as ExpandAxiosResponse;
    return res.data;
  },

  // 响应拦截
  responseInterceptorCatch(err) {
    return Promise.reject(err.response);
  },
};
const request = new MyRequest({
  baseURL: "",
  timeout: 5000,
  interceptorHooks: transform,
});

export default request;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

在组件中使用

// 定义请求返回
interface ResModel {
  str: string
  num: number
}
// 发起请求
request
  .post<ResModel>(
    '/abc',
    {
      a: 'aa',
      b: 'bb'
    },
    {
      requestOptions: {
        globalErrorMessage: true
      }
    }
  )
  .then((res) => {
    console.log('res: ', res)
    console.log(res.str)
  })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号