如何使用 Class +TypeScript对axios进行封装

提示:以下是本篇文章正文内容,下面案例可供参考

一、安装axios和ts相关环境

本文是在react项目中进行封装的,当然也可以在vue项目中使用。

npm install axios

二、判断是否是生产环境或者是线上环境

1.我们以webpack为例子

通过process.env.NODE_ENV就可以判断出我们的项目处于什么样的环境下面

let BASE_URL = ''
const TIME_OUT = 10000

if (process.env.NODE_ENV === 'development') {
  BASE_URL = 'http://localhost:3000'
} else if (process.env.NODE_ENV === 'production') {
  BASE_URL = 'http://localhost:3001'
} else if (process.env.NODE_ENV === 'test') {
  BASE_URL = 'http://localhost:3002'
}

export { BASE_URL, TIME_OUT }

2.安装请求之前的动画:NProgress

import NProgress from 'nprogress'
export default NProgress

3.进行类型限制

我们对axios进行一些拓展,我们不仅仅他的实例有拦截器,我们可以给他进行传入拦截器,还可

以控制这个请求动画是否需要有。

import type { AxiosRequestConfig } from 'axios'

export interface LHRequestInterceptors {
  requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorCatch?: (error: any) => any
  responseInterceptor?: (res: any) => any
  responseInterceptorCatch?: (error: any) => any
}

export interface LHRequestConfig extends AxiosRequestConfig {
  interceptors?: LHRequestInterceptors
  showLoading?: boolean
}

4.封装class请求工具类

import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { LHRequestConfig, LHRequestInterceptors } from './type'
import NProgress from './myNprogress'

const defaultLoading = true

class LHRequest {
  instance: AxiosInstance
  interceptors?: LHRequestInterceptors
  showLoading?: boolean

  constructor(config: LHRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? defaultLoading

    //所有实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptorCatch,
      this.interceptors?.responseInterceptor
    )
    //全局的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          NProgress.start()
        }
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        if (this.showLoading) {
          NProgress.done()
        }
        return res.data
      },
      (err) => {
        return err
      }
    )
  }
  request<T>(config: LHRequestConfig): Promise<T> {
    return new Promise((reslove, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          this.showLoading = true
          reslove(res)
        })
        .catch((err) => {
          this.showLoading = true
          reject(err)
          return err
        })
    })
  }
  get<T>(config: LHRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T>(config: LHRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
  delet<T>(config: LHRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }
  patch<T>(config: LHRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}
export default LHRequest

4.New一个他的实例方便管理

// service的统一出口
import { BASE_URL, TIME_OUT } from './request/config'
import LHRequest from './request'
const lhRequest = new LHRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      console.log('成功的拦截')
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res
    },
    responseInterceptorCatch(err) {
      return err
    }
  }
})
export default lhRequest

5.如何调用

lhRequest
    .get<banner>({
      url: '/dj/banner',
      showLoading: true
    })
    .then((res) => {
      console.log(res.data)
    })

猜你喜欢

转载自blog.csdn.net/m0_70718568/article/details/128519514