一.axios 封装技巧,如何高度复用

64 阅读1分钟

在开发中,为了提高效率,通常对axios进行封装,简化了请求的发送和对响应的处理。同时,统一错误处理机制有助于维护代码的清晰和一致性。本文介绍了一些高效封装 Axios 请求的方法。

封装思路

以插件形式进行封装,每个插件解决一个问题,这种封装可复用多个axios实例,在多个项目中复用

var instance1= axios.create({
    baseURL: '/api1,
  timeout: 20000
})

 var instance2= axios.create({
    baseURL: '/api2
  timeout: 20000
})
// instance2复用
// handleInterceptorState(instance2)

// 处理响应数据
handleInterceptorState(instance1)

// 处理错误
handleResponseError(instance1)

处理响应数据

//使用方式
instance({
    url: '/api/get',
    method: 'GET',
    noHandleResponse: true, //不需要处理响应
})

const isShow = response => response.data.IsSuccess

const showMessage = response => {
  if (isShow(response)) {
    return false
  }

  ElNotification({
    type: "error",
    title: "请求失败",
    message: response.data.Message
  })

  return true
}

// 处理响应状态
function handleInterceptorState(instance) {
  instance.interceptors.response.use(response => {
  
      // 直接原样返回
    if (response.config.noHandleResponse) {
      return response
    }
    //返回data
    if (response.config.noHandleCode) {
      return response.data
    }

    showMessage(response)

    if (isShow(response)) {
      return response.data
    }

    return response
  })
}

处理错误

let errorStatus = {
  400: '错误请求',
  401: '请求未授权',
  403: '服务器拒绝请求',
  404: '服务器未找到请求',
  405: '方法禁用',
  406: '无法使用请求的内容特性',
  500: '服务器内部错误',
  501: '尚未实施',
  502: '错误网关',
  503: '服务不可用',
  504: '网关超时',
  505: 'HTTP 版本不受支持',
}

function handleResponseError(instance) {
  instance.interceptors.response.use(undefined, error => {
    let { response } = error
    if (!response) {
      ElNotification({
        type: 'error',
        title: '请求失败',
        message: '请求超时'
      })
      return Promise.reject(error)
    }
    let errorMessage = errorStatus[response.status]

    if (errorMessage) {
      if (/^5/.test(response.status)) {
        errorMessage += `; 状态码: ${response.status},请联系管理员`
      }
      ElNotification({
        type: 'error',
        title: '请求失败',
        message: errorMessage
      })
    }
    return Promise.reject(error)
  })
}