Vue3中axios的简单封装

247 阅读4分钟

Vue3学习日记—axios的封装

前言

​ 今天是2022年1月15日,昨天下午刚刚考完毛概,寒假终于来了。14号才放寒假,太惨了,这次寒假只有36天。从今天开始也正式恢复更新了,下学期晚上没有公选课,时间应该更加充裕些。今天我们来看对axios经行一下封装。

1.axios的安装

​ 先简单介绍一下axios吧。以下内容来自官网。

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

​ axios应该是目前前端用的较多的网络请求库了。安装也很简单。

npm install axios -D

​ 安装完成之后,就可以在文件里面直接引入使用了。

2.文件结构

​ 在项目中,我们一般都是把网络请求相关的代码全部放到一个文件夹里面,文件夹取名service

文件结构目录

​ service——index.ts (文件夹的出口文件,一般都命名为index.ts)

​ ——request ——config.ts(axios的一些基础配置)

​ ——index.ts (经行封装的文件)

​ ——type.ts(类型文件)

3.request中config.ts的配置

​ 在config.ts文件中,主要配置baseurl和timeout等一些axios的基础属性,和不同环境下baseurl地址。

let BASE_URL = ''
const TIME_OUT = 10000

if (process.env.NODE_ENV === 'development') {
  BASE_URL = 'url地址'
} else if (process.env.NODE_ENV === 'production') {
  BASE_URL = 'url地址'
} else {
  BASE_URL = 'rul地址'
}
export { BASE_URL, TIME_OUT }

4.request中index.ts的配置

​ 由于axios中的方法配置较多,因此这里我们选择通过类的方法,将axios里的各个方法重新封装到一个实例中,并在此基础上可以扩展我们自己的一些需求。

mport axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
// 添加拦截器
// 这里我们我们创建一个拦截器的接口
interface HxRequestInterceptors {
  requestInterceptor: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorCatch: (err: any) => any
  responseInterceptor: (res: AxiosResponse) => AxiosResponse
  responseInterceptorCatch: (err: any) => any
}
// 创建一个新的接口继承自AxiosRequestConfig
interface HxRequestConfig extends AxiosRequestConfig {
  interceptors: HxRequestInterceptors
}
class HxRequest {
  instance: AxiosInstance
  interceptors: HxRequestInterceptors
  constructor(config: HxRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    // 在创建的axios上使用request拦截器
    this.instance.interceptors.request.use(
      this.interceptors.requestInterceptor,
      this.interceptors.requestInterceptorCatch
    )
    // 在创建的axios上使用response拦截器
    this.instance.interceptors.response.use(
      this.interceptors.responseInterceptor,
      this.interceptors.responseInterceptorCatch
    )
  }
}

export default HxRequest

注意

​ 在Axios提供的类型AxiosRequestConfig里面是没有interceptors这一个选项的。下面为axios中AxiosRequestConfig接口中的配置。

export interface AxiosRequestConfig<D = any> {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
  transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
  headers?: AxiosRequestHeaders;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: D;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: ((status: number) => boolean) | null;
  maxBodyLength?: number;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
  decompress?: boolean;
  transitional?: TransitionalOptions;
  signal?: AbortSignal;
  insecureHTTPParser?: boolean;
}

​ 而为了使我们所使用的接口有interceptors这一个属性,我们可以采用以下的步骤。

1.创建一个新接口HxRequestInterceptors。在这个接口中我们可以放入我们的拦截器函数的配置

2.创建一个新接口 HxRequestConfig 并继承自 AxiosRequestConfig。然后,在HxRequetConfig中的配置interceptors的属性 类型注解为 HxRequestInterceptors。根据接口的继承规则,就成功的将我们所要添加的接口加到了原AxiosRequesConfig中。并得到了两者的结合 HxRequestConfig。这样我们就可以直接使用我们这个新创建的接口了.

​ 但是这样写,当我们所要添加的属性较多时,index里面的内容就会显得臃肿,因此我们可以将所有的接口信息单独拎出来。这样我们就还需要一个type.ts

5.type.ts的配置

​ type.ts主要就是放接口的地方,我们直接从index里面截取就可以了。

import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface HxRequestInterceptors {
  requestInterceptor: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorCatch: (err: any) => any
  responseInterceptor: (res: AxiosResponse) => AxiosResponse
  responseInterceptorCatch: (err: any) => any
}
// 创建一个新的接口继承自AxiosRequestConfig
export interface HxRequestConfig extends AxiosRequestConfig {
  interceptors: HxRequestInterceptors
}

6.index.ts的配置

​ 在index里面,我们只需要new出我们在request文件夹中的index里面的类就可以了。然后把这个new出来的对象导出去,这样我们就可以在我们需要的地方使用我们封装号的Axios库了。

import HxRequest from './requestcopy/index'
import { BASE_URL, TIME_OUT } from './request/config'
const hxRequest = new HxRequest({
  url: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res
    },
    responseInterceptorCatch: (err) => {
      return err
    }
  }
})

export default hxRequest

总结

​ 之后,我们就只需要通过new出一个实例就可以使用我们封装好的axios库了。当然,并不是每个请求 都要拦截器,这个可以直接用可选链。代码我就不继续贴了。