axios ts 封装 比较简洁的封装 大部分场景够使用

104 阅读1分钟

axios ts 封装 比较简洁的封装 大部分场景够使用

import type { AxiosError } from 'axios'
import axios, { type AxiosRequestConfig } from 'axios'
import { message, notification } from 'ant-design-vue'
import { getCookie, IS_DEV } from 'common/utils'
import { MEDICINE_BASE_API } from '@/config'

const codeMessage: Record<number, string> = {
  400: '请求错误',
  401: '无访问权限',
  403: '请求错误',
  404: '请求不存在',
  406: '请求的格式不可得',
  410: '请求的资源被永久删除',
  422: '当创建一个对象时,发生一个验证错误',
  500: '服务器发生错误,请检查服务器',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维护',
  504: '网关超时。'
}

const errorHandler = async (error: AxiosError) => {
  const { response, code } = error
  if (response?.status) {
    const statusText = codeMessage[response.status] || response.statusText
    const { status } = response
    notification.error({
      message: `请求错误 ${status}`,
      description: statusText
    })
  } else if (code === 'ERR_NETWORK') {
    notification.error({
      message: '网络连接失败,请检查网络'
    })
  }
  throw error
}

const axiosInstance = axios.create({
  baseURL: IS_DEV ? '' : MEDICINE_BASE_API,
  timeout: 10 * 60 * 1000
})

axiosInstance.interceptors.request.use((config) => {
  config.headers.set({
    Authorization:
      getCookie('admin_token')! ??
      localStorage.getItem('token')!
  })
  return config
}, errorHandler)

axiosInstance.interceptors.response.use((res) => {
  const { status, data } = res
  if (status === 200) {
    // export
    if (data instanceof ArrayBuffer) {
      return {
        contentDisposition: res.headers['content-disposition'],
        data
      }
    }
    /* OSS */
    if (data instanceof Blob || typeof data === 'string') return data
    const { code, message: msg } = data
    if (code === 0) return data
    if (code === 1016) {
      // window.location.href = '/'
      // TODO: use navigate('/login')
      // window.location.reload()
    } else {
      message.error(msg)
    }
  }
  return data
}, errorHandler)

export const request = <T>(config: AxiosRequestConfig) => axiosInstance.request<unknown, T>(config)