用TS封装了一个axios,支持全局拦截、实例拦截、单个请求拦截、loading等待功能

先给拍一张结构图

 最外层 index.ts统一出口

request文件夹中的 config.ts进行了baseurl和响应时间等基础配置

request文件夹中的index.ts就是我们主要的axios封装问加啦

 最外层 index.ts

// service统一出口
import HYRequest from './request'
import {BASE_URL,TIME_OUT} from './request/config'

const hyRequest = new HYRequest({
  baseURL:BASE_URL,
  timeout: TIME_OUT
})

export default hyRequest

request文件夹中的 config.ts

// 环境
let BASE_URL = ''
let 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 = ''
} else {
  BASE_URL = ''
}

export {BASE_URL, TIME_OUT}

request文件夹中的index.ts

import axios from 'axios'
import type {AxiosInstance,AxiosRequestConfig,AxiosResponse} from 'axios'

import { ElLoading } from 'element-plus';
import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

const DEAFULT_LOADING = true

// 定义接口,四个函数类型
interface HYRequestInterceptors<T = AxiosResponse> {
  requestInterceptor?:(config:AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorCatcher?:(error:any) => any
  responseInterceptor?:(res:T) => T
  responseInterceptorCatcher?:(error:any) => any
}
// 继承AxiosRequestConfig接口,增加HYRequestInterceptors接口类型
interface HYRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
  interceptors?:HYRequestInterceptors<T>
  showLoading?: boolean
}
// 使用class进行封装
class HYRequest{
  instance:AxiosInstance
  interceptors?:HYRequestInterceptors
  showLoading: boolean
  loading?:ILoadingInstance
  // 构造器
  constructor(config:HYRequestConfig){
    // 创建axios实例
    this.instance = axios.create(config)
    // 保存基本信息
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? DEAFULT_LOADING
    /**1.从config中取出的拦截器是对应实例的拦截器 */
    // 使用请求拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatcher
    )
    // 使用响应拦截器
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatcher
    )

    /**2.添加所有实例都有的拦截器 */
    this.instance.interceptors.request.use(
      (config)=>{
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock:true,
            text:'正在加载中...',
            background:'rgba(0,0,0,0.5)'
          });
        }
        
        return config
      },
      (err)=>{
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res)=>{
        // 讲loading移除
        this.loading?.close();

        return res.data
      },
      (err)=>{
        // 讲loading移除
        this.loading?.close();

        return err
      }
    )
  }

  request<T>(config:HYRequestConfig<T>):Promise<T> {
    return new Promise((resolve,reject) => {
      // 单个请求对请求config的处理
    if (config.interceptors?.requestInterceptor) {
      config = config.interceptors.requestInterceptor(config)
    }
    // 判断是否需要显示loading
    if (config.showLoading === false) {
      this.showLoading = config.showLoading
    }

    this.instance
      .request<any,T>(config)
      .then((res) => {
      // 1.单个请求对返回数据的处理
      if (config.interceptors?.responseInterceptor) {
        // res = config.interceptors.responseInterceptor(res)
      }
      // 2.将showLoading设置成true,这样不会影响到下一个请求
      this.showLoading = DEAFULT_LOADING;
      // 3.将结果resolve返回出去
      resolve(res)
    }).catch(err => {
      // 将showLoading设置成true,这样不会影响到下一个请求
      this.showLoading = DEAFULT_LOADING;
      reject(err)
      return err
    })
    })
  }

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

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

  patch<T>(config:HYRequestConfig<T>):Promise<T> {
    return this.request<T>({...config, method:'patch'})
  }

  get<T>(config:HYRequestConfig<T>):Promise<T> {
    return this.request<T>({...config, method:'get'})
  }

}

export default HYRequest;

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值