[Typescript]简易封装Axios

[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",
      },
    });
  }
}

实例化并导出

先实例化一个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;

在组件中使用

// 定义请求返回
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)
  })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值