项目中使用Typescript封装axios

目录
  • 写在前面
  • 基础封装
  • 拦截器封装
    • 类拦截器
    • 实例拦截器
    • 接口拦截
  • 封装请求方法
  • 取消请求
    • 准备工作
    • 取消请求方法的添加与删除
    • 取消请求方法
  • 测试
    • 测试请求方法
    • 测试取消请求
  • 写在最后

写在前面

虽然说Fetch API已经使用率已经非常的高了,但是在一些老的浏览器还是不支持的,而且axios仍然每周都保持2000多万的下载量,这就说明了axios仍然存在不可撼动的地位,接下来我们就一步一步的去封装,实现一个灵活、可复用的一个请求请发。

这篇文章封装的axios已经满足如下功能:

  • 无处不在的代码提示;
  • 灵活的拦截器;
  • 可以创建多个实例,灵活根据项目进行调整;
  • 每个实例,或者说每个接口都可以灵活配置请求头、超时时间等;
  • 取消请求(可以根据url取消单个请求也可以取消全部请求)。

基础封装

首先我们实现一个最基本的版本,实例代码如下:

// index.ts
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
class Request {
  // axios 实例
  instance: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)
  }
  request(config: AxiosRequestConfig) {
    return this.instance.request(config)
  }
}
export default Request

这里将其封装为一个类,而不是一个函数的原因是因为类可以创建多个实例,适用范围更广,封装性更强一些。

拦截器封装

首先我们封装一下拦截器,这个拦截器分为三种:

  • 类拦截器
  • 实例拦截器
  • 接口拦截器

接下来我们就分别实现这三个拦截器。

类拦截器

类拦截器比较容易实现,只需要在类中对axios.create()创建的实例调用interceptors下的两个拦截器即可,实例代码如下:

// index.ts
constructor(config: AxiosRequestConfig) {
  this.instance = axios.create(config)
  this.instance.interceptors.request.use(
    (res: AxiosRequestConfig) => {
      console.log('全局请求拦截器')
      return res
    },
    (err: any) => err,
  )
  this.instance.interceptors.response.use(
    // 因为我们接口的数据都在res.data下,所以我们直接返回res.data
    (res: AxiosResponse) => {
      console.log('全局响应拦截器')
      return res.data
    },
    (err: any) => err,
  )
}

我们在这里对响应拦截器做了一个简单的处理,就是将请求结果中的.data进行返回,因为我们对接口请求的数据主要是存在在.data中,跟data同级的属性我们基本是不需要的。

实例拦截器

实例拦截器是为了保证封装的灵活性,因为每一个实例中的拦截后处理的操作可能是不一样的,所以在定义实例时,允许我们传入拦截器。

首先我们定义一下interface,方便类型提示,代码如下:

// types.ts
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
export interface RequestInterceptors {
  // 请求拦截
  requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorsCatch?: (err: any) => any
  // 响应拦截
  responseInterceptors?: (config: AxiosResponse) => AxiosResponse
  responseInterceptorsCatch?: (err: any) => any
}
// 自定义传入的参数
export interface RequestConfig extends AxiosRequestConfig {
  interceptors?: RequestInterceptors
}

定义好基础的拦截器后,我们需要改造我们传入的参数的类型,因为axios提供的AxiosRequestConfig是不允许我们传入拦截器的,所以说我们自定义了RequestConfig,让其继承与AxiosRequestConfig

剩余部分的代码也比较简单,如下所示:

// index.ts
import axios, { AxiosResponse } from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import type { RequestConfig, RequestInterceptors } from './types'
class Request {
  // axios 实例
  instance: AxiosInstance
  // 拦截器对象
  interceptorsObj?: RequestInterceptors
  constructor(config: RequestConfig) {
    this.instance = axios.create(config)
    this.interceptorsObj = config.interceptors
    this.instance.interceptors.request.use(
      (res: AxiosRequestConfig) => {
        console.log('全局请求拦截器')
        return res
      },
      (err: any) => err,
    )
    // 使用实例拦截器
    this.instance.interceptors.request.use(
      this.interceptorsObj?.requestInterceptors,
      this.interceptorsObj?.requestInterceptorsCatch,
    )
    this.instance.interceptors.response.use(
      this.interceptorsObj?.responseInterceptors,
      this.interceptorsObj?.responseInterceptorsCatch,
    )
    // 全局响应拦截器保证最后执行
    this.instance.interceptors.response.use(
      // 因为我们接口的数据都在res.data下,所以我们直接返回res.data
      (res: AxiosResponse) => {
        console.log('全局响应拦截器')
        return res.data
      },
      (err: any) => err,
    )
  }
}

我们的拦截器的执行顺序为实例请求→类请求→实例响应→类响应;这样我们就可以在实例拦截上做出一些不同的拦截,

接口拦截

现在我们对单一接口进行拦截操作,首先我们将AxiosRequestConfig类型修改为RequestConfig允许传递拦截器;

然后我们在类拦截器中将接口请求的数据进行了返回,也就是说在request()方法中得到的类型就不是AxiosResponse类型了。

我们查看axios的index.d.ts中,对request()方法的类型定义如下:

// type.ts
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;

也就是说它允许我们传递类型,从而改变request()方法的返回值类型,我们的代码如下:

// index.ts
request<T>(config: RequestConfig): Promise<T> {
  return new Promise((resolve, reject) => {
    // 如果我们为单个请求设置拦截器,这里使用单个请求的拦截器
    if (config.interceptors?.requestInterceptors) {
      config = config.interceptors.requestInterceptors(config)
    }
    this.instance
      .request<any, T>(config)
      .then(res => {
        // 如果我们为单个响应设置拦截器,这里使用单个响应的拦截器
        if (config.interceptors?.responseInterceptors) {
          res = config.interceptors.responseInterceptors<T>(res)
        }
        resolve(res)
      })
      .catch((err: any) => {
        reject(err)
      })
  })
}

这里还存在一个细节,就是我们在拦截器接受的类型一直是AxiosResponse类型,而在类拦截器中已经将返回的类型改变,所以说我们需要为拦截器传递一个泛型,从而使用这种变化,修改types.ts中的代码,示例如下:

// index.ts
export interface RequestInterceptors {
  // 请求拦截
  requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorsCatch?: (err: any) => any
  // 响应拦截
  responseInterceptors?: <T = AxiosResponse>(config: T) => T
  responseInterceptorsCatch?: (err: any) => any
}

请求接口拦截是最前执行,而响应拦截是最后执行。

封装请求方法

现在我们就来封装一个请求方法,首先是类进行实例化示例代码如下:

// index.ts
import Request from './request'
const request = new Request({
  baseURL: import.meta.env.BASE_URL,
  timeout: 1000 * 60 * 5,
  interceptors: {
    // 请求拦截器
    requestInterceptors: config => {
      console.log('实例请求拦截器')
      return config
    },
    // 响应拦截器
    responseInterceptors: result => {
      console.log('实例响应拦截器')
      return result
    },
  },
})

然后我们封装一个请求方法, 来发送网络请求,代码如下:

// src/server/index.ts
import Request from './request'
import type { RequestConfig } from './request/types'
interface YWZRequestConfig<T> extends RequestConfig {
  data?: T
}
interface YWZResponse<T> {
  code: number
  message: string
  data: T
}
/**
 * @description: 函数的描述
 * @interface D 请求参数的interface
 * @interface T 响应结构的intercept
 * @param {YWZRequestConfig} config 不管是GET还是POST请求都使用data
 * @returns {Promise}
 */
const ywzRequest = <D, T = any>(config: YWZRequestConfig<D>) => {
  const { method = 'GET' } = config
  if (method === 'get' || method === 'GET') {
    config.params = config.data
  }
  return request.request<YWZResponse<T>>(config)
}
export default ywzRequest

该请求方式默认为GET,且一直用data作为参数;

取消请求

应评论区@Pic@Michaelee@Alone_Error的建议,这里增加了一个取消请求;关于什么是取消请求可以参考官方文档

准备工作

我们需要将所有请求的取消方法保存到一个集合(这里我用的数组,也可以使用Map)中,然后根据具体需要去调用这个集合中的某个取消请求方法。

首先定义两个集合,示例代码如下:

// index.ts
import type {
  RequestConfig,
  RequestInterceptors,
  CancelRequestSource,
} from './types'
class Request {
  /*
  存放取消方法的集合
  * 在创建请求后将取消请求方法 push 到该集合中
  * 封装一个方法,可以取消请求,传入 url: string|string[]
  * 在请求之前判断同一URL是否存在,如果存在就取消请求
  */
  cancelRequestSourceList?: CancelRequestSource[]
  /*
  存放所有请求URL的集合
  * 请求之前需要将url push到该集合中
  * 请求完毕后将url从集合中删除
  * 添加在发送请求之前完成,删除在响应之后删除
  */
  requestUrlList?: string[]
  constructor(config: RequestConfig) {
    // 数据初始化
    this.requestUrlList = []
    this.cancelRequestSourceList = []
  }
}

这里用的CancelRequestSource接口,我们去定义一下:

// type.ts
export interface CancelRequestSource {
  [index: string]: () => void
}

这里的key是不固定的,因为我们使用urlkey,只有在使用的时候才知道url,所以这里使用这种语法。

取消请求方法的添加与删除

首先我们改造一下request()方法,它需要完成两个工作,一个就是在请求之前将url和取消请求方法push到我们前面定义的两个属性中,然后在请求完毕后(不管是失败还是成功)都将其进行删除,实现代码如下:

// index.ts
request<T>(config: RequestConfig): Promise<T> {
  return new Promise((resolve, reject) => {
    // 如果我们为单个请求设置拦截器,这里使用单个请求的拦截器
    if (config.interceptors?.requestInterceptors) {
      config = config.interceptors.requestInterceptors(config)
    }
    const url = config.url
    // url存在保存取消请求方法和当前请求url
    if (url) {
      this.requestUrlList?.push(url)
      config.cancelToken = new axios.CancelToken(c => {
        this.cancelRequestSourceList?.push({
          [url]: c,
        })
      })
    }
    this.instance
      .request<any, T>(config)
      .then(res => {
        // 如果我们为单个响应设置拦截器,这里使用单个响应的拦截器
        if (config.interceptors?.responseInterceptors) {
          res = config.interceptors.responseInterceptors<T>(res)
        }
        resolve(res)
      })
      .catch((err: any) => {
        reject(err)
      })
      .finally(() => {
        url && this.delUrl(url)
      })
  })
}

这里我们将删除操作进行了抽离,将其封装为一个私有方法,示例代码如下:

// index.ts
/**
 * @description: 获取指定 url 在 cancelRequestSourceList 中的索引
 * @param {string} url
 * @returns {number} 索引位置
 */
private getSourceIndex(url: string): number {
  return this.cancelRequestSourceList?.findIndex(
    (item: CancelRequestSource) => {
      return Object.keys(item)[0] === url
    },
  ) as number
}
/**
 * @description: 删除 requestUrlList 和 cancelRequestSourceList
 * @param {string} url
 * @returns {*}
 */
private delUrl(url: string) {
  const urlIndex = this.requestUrlList?.findIndex(u => u === url)
  const sourceIndex = this.getSourceIndex(url)
  // 删除url和cancel方法
  urlIndex !== -1 && this.requestUrlList?.splice(urlIndex as number, 1)
  sourceIndex !== -1 &&
    this.cancelRequestSourceList?.splice(sourceIndex as number, 1)
}

取消请求方法

现在我们就可以封装取消请求和取消全部请求了,我们先来封装一下取消全部请求吧,这个比较简单,只需要调用this.cancelRequestSourceList中的所有方法即可,实现代码如下:

// index.ts
// 取消全部请求
cancelAllRequest() {
  this.cancelRequestSourceList?.forEach(source => {
    const key = Object.keys(source)[0]
    source[key]()
  })
}

现在我们封装一下取消请求,因为它可以取消一个和多个,那它的参数就是url,或者包含多个URL的数组,然后根据传值的不同去执行不同的操作,实现代码如下:

// index.ts
// 取消请求
cancelRequest(url: string | string[]) {
  if (typeof url === 'string') {
    // 取消单个请求
    const sourceIndex = this.getSourceIndex(url)
    sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][url]()
  } else {
    // 存在多个需要取消请求的地址
    url.forEach(u => {
      const sourceIndex = this.getSourceIndex(u)
      sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][u]()
    })
  }
}

测试

测试请求方法

现在我们就来测试一下这个请求方法,这里我们使用www.apishop.net/提供的免费API进行测试,测试代码如下:

<script setup lang="ts">
// app.vue
import request from './service'
import { onMounted } from 'vue'
interface Req {
  apiKey: string
  area?: string
  areaID?: string
}
interface Res {
  area: string
  areaCode: string
  areaid: string
  dayList: any[]
}
const get15DaysWeatherByArea = (data: Req) => {
  return request<Req, Res>({
    url: '/api/common/weather/get15DaysWeatherByArea',
    method: 'GET',
    data,
    interceptors: {
      requestInterceptors(res) {
        console.log('接口请求拦截')
        return res
      },
      responseInterceptors(result) {
        console.log('接口响应拦截')
        return result
      },
    },
  })
}
onMounted(async () => {
  const res = await get15DaysWeatherByArea({
    apiKey: import.meta.env.VITE_APP_KEY,
    area: '北京市',
  })
  console.log(res.result.dayList)
})
</script>

如果在实际开发中可以将这些代码分别抽离。

上面的代码在命令中输出

接口请求拦截
实例请求拦截器
全局请求拦截器
实例响应拦截器
全局响应拦截器
接口响应拦截
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

测试取消请求

首先我们在.server/index.ts中对取消请求方法进行导出,实现代码如下:

// 取消请求
export const cancelRequest = (url: string | string[]) => {
  return request.cancelRequest(url)
}
// 取消全部请求
export const cancelAllRequest = () => {
  return request.cancelAllRequest()
}

然后我们在app.vue中对其进行引用,实现代码如下:

<template>
  <el-button
    @click="cancelRequest('/api/common/weather/get15DaysWeatherByArea')"
    >取消请求</el-button
  >
  <el-button @click="cancelAllRequest">取消全部请求</el-button>
  <router-view></router-view>
</template>
<script setup lang="ts">
import request, { cancelRequest, cancelAllRequest } from './service'
</script>

发送请求后,点击按钮即可实现对应的功能

写在最后

本篇文章到这里就结束了,如果文章对你有用,可以三连支持一下,如果文章中有错误或者说你有更好的见解,欢迎指正~

项目地址:ywanzhou/vue3-template (github.com)

以上就是项目中使用Typescript封装axios的详细内容,更多关于Typescript封装axios的资料请关注我们其它相关文章!

(0)

相关推荐

  • Vue3中使用typescript封装axios的实例详解

    这个axios封装,因为是用在vue3的demo里面的,为了方便,在vue3的配置里面按需加载element-plus 封装axios http.ts import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios' import { IResponseData } from '@/types' import { ElMessage, ElLoading, ILoadingInstance

  • TypeScript利用TS封装Axios实战

    目录 简介 Axios几个常用类型 AxiosRequestConfig AxiosInstance AxiosStatic AxiosResponse AxiosError 基础封装 拦截器封装 常用方法封装 总结 简介 这是TypeScript实战的第三篇文章.前面两篇笔者分别介绍了在Vuex和Pinia中怎么使用TypeScript以及Vuex和Pinia的区别.今天我们再用TypeScript封装一遍Axios.希望能进一步巩固TypeScript的基础知识. Axios几个常用类型 在

  • 关于Vue中axios的封装实例详解

    前言 axios 是 Vue 官方推荐的一个 HTTP 库,用 axios 官方简介来介绍它,就是: Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. 作为一个优秀的 HTTP 库,axios 打败了曾经由 Vue 官方团队维护的 vue-resource,获得了 Vue 作者尤小右的大力推荐,成为了 Vue 项目中 HTTP 库的最佳选择. 虽然,axios 是个优秀的 HTTP 库,但是,直接在项目中使用并不是那么方便,所以,我们需要对其进行一

  • vue+ts下对axios的封装实现

    虽然vue中axios的使用已经十分方便,但是实际我们的日常操作中可能为了接口的规则一致,来创建一个统一管理的全局方法达到简化操作.而且在实际接口对接中,我们大多都需要对请求和响应进行拦截来进行token以及回调状态码的处理.那么我基于自己的需求简单分装了一下.(之前很少接触vue,主要用的ng和react,这次新项目想用vue来弄,熟悉一下vue的一些新特性和方法,有啥不对的,欢迎大家批评指正) 前提: 熟悉前端ts, node等等. 1. 安装axios npm install axios

  • 基于Typescript与Axios的接口请求管理详解

    目录 思路 请求拦截 响应拦截 使用httpClient.ts定义请求 在组件中请求接口 总结 本文主要介绍基于TS和AXIOS的接口请求封装 思路 请求拦截 在请求头添加一些参数,例如token,uid等 判断用户登录状态,如果没有登录,直接跳转登录 处理请求数据转换发送请求的数据格式,json→urlencoded (可选的) 响应拦截 判断后端响应的业务状态码,进行不同的处理 例如用户登录状态过期,直接跳转登录 统一的报错提示 先把套路化的代码写出来: import axios, { Ax

  • 项目中使用Typescript封装axios

    目录 写在前面 基础封装 拦截器封装 类拦截器 实例拦截器 接口拦截 封装请求方法 取消请求 准备工作 取消请求方法的添加与删除 取消请求方法 测试 测试请求方法 测试取消请求 写在最后 写在前面 虽然说Fetch API已经使用率已经非常的高了,但是在一些老的浏览器还是不支持的,而且axios仍然每周都保持2000多万的下载量,这就说明了axios仍然存在不可撼动的地位,接下来我们就一步一步的去封装,实现一个灵活.可复用的一个请求请发. 这篇文章封装的axios已经满足如下功能: 无处不在的代

  • Vue3+TypeScript封装axios并进行请求调用的实现

    不是吧,不是吧,原来真的有人都2021年了,连TypeScript都没听说过吧?在项目中使用TypeScript虽然短期内会增加一些开发成本,但是对于其需要长期维护的项目,TypeScript能够减少其维护成本,使用TypeScript增加了代码的可读性和可维护性,且拥有较为活跃的社区,当居为大前端的趋势所在,那就开始淦起来吧~ 使用TypeScript封装基础axios库 代码如下: // http.ts import axios, { AxiosRequestConfig, AxiosRes

  • 在React项目中使用TypeScript详情

    目录 项目目录及ts文件划分 在项目中使用TypeScript具体实践 组件声明 React Hooks使用 useState useRef useCallback useMemo useContext useReducer useImperativeHandle Axios请求/响应定义封装 前言: 本文主要记录我如何在React项目中优雅的使用TypeScript,来提高开发效率及项目的健壮性. 项目目录及ts文件划分 由于我在实际项目中大部分是使用umi来进行开发项目,所以使用umi生成的

  • 在Vue中是如何封装axios

    目录 1.安装 1.引入 3.接口根地址 4.使用事例 4.1下载 4.2get 4.3post 1.安装 npm install axios; // 安装axios 1.引入 import axios from 'axios' 3.接口根地址 const baseUrl = API_BASE_URL // 由webpack的插件DefinePlugin注入 webpackConfig .plugin('define') .use(require('webpack/lib/DefinePlugi

  • 在Vue项目中使用Typescript的实现

    3.0迟迟没有发布release版本,现阶段在Vue项目中使用Typescript需要花不小的精力在工程的配置上面.主要的工作是webpack对TS,TSX的处理,以及2.x版本下面使用class的形式书写Vue 组件的一些限制和注意事项. Webpack 配置 配置webpack对TS,TSX的支持,以便于我们在Vue项目中使用Typescript和tsx. module.exports = { entry: './index.vue', output: { filename: 'bundle

  • vue中如何简单封装axios浅析

    把axios注入到Vue中 import axios from 'axios'; Vue.prototype.$axios = axios; import axios from 'axios' axios.defaults.timeout = 5000; //响应时间 axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'; //配置请求头 axios.defaults.withCredenti

  • 如何在Vue项目中应用TypeScript类

    目录 一.前言 二.使用 1.@Component 2.compued.data.methods 3.@props 4.@watch 5.@emit 三 .总结 一.前言 TypeScript是基于vue-class-component库而来,这个库vue官方推出的一个支持使用class方式来开发vue单文件组件的库 主要的功能如下: methods 可以直接声明为类的成员方法 计算属性可以被声明为类的属性访问器 初始化的 data 可以被声明为类属性 data.render 以及所有的 Vue

  • React项目中应用TypeScript的实现

    目录 一.前言 二.使用方式 无状态组件 有状态组件 受控组件 三.总结 一.前言 单独的使用typescript 并不会导致学习成本很高,但是绝大部分前端开发者的项目都是依赖于框架的 例如和vue.react 这些框架结合使用的时候,会有一定的门槛 使用 TypeScript 编写 react 代码,除了需要 typescript 这个库之外,还需要安装@types/react.@types/react-dom npm i @types/react -s npm i @types/react-

  • Typescript 封装 Axios拦截器方法实例

    目录 引言 创建 class axios.create([config]) 封装 request(config)通用方法 封装-拦截器(单个实例独享) 扩展 Http 自定义拦截器 封装-拦截器(所有实例共享) 封装-拦截器(单个请求独享) 装修 Http class 返回经过 request 返回数据结构(DTO) 拦截器执行顺序 操作场景控制 引言 对 axios 二次封装,更加的可配置化.扩展性更加强大灵活 通过 class 类实现,class 具备更强封装性(封装.继承.多态),通过实例

随机推荐