基于-axios-的封装请求

42次阅读

共计 1358 个字符,预计需要花费 4 分钟才能阅读完成。

import axios from 'axios'

const baseURL = process.env.NODE_ENV === 'development'
  ? 'http://localhost:4000'
  : 'http://localhost:4000'

axios.interceptors.request.use(
  config => {
    let requestName = config.data.requestName
    if (requestName) {if (axios[requestName] && axios[requestName].cancel) {axios[requestName].cancel(`${requestName} 请求被取消 `)
      }
      config.cancelToken = new axios.CancelToken(c => {axios[requestName] = {}
        axios[requestName].cancel = c
      })
    }
    return config
  }, 
  error => {return Promise.reject(error)
  }
)


axios.interceptors.response.use(
  config => {return config}, 
  error => {console.log(error)
    let errMsg = ''

    if (error && error.response) {
      const map = new Map([[400, '错误请求'],
        [401, '未授权,请重新登录'],
        [403, '拒绝访问'],
        [404, '请求错误, 未找到该资源'],
        [405, '请求方法未允许'],
        [408, '请求超时'],
        [500, '服务器端出错'],
        [501, '网络未实现'],
        [502, '网络错误'],
        [503, '服务不可用'],
        [504, '网络超时'],
        [505, 'http 版本不支持该请求']
      ])
      const defaultErrorMsg = ` 连接错误,服务器返回的状态码为 ${error.response.status}`
      errMsg = map.get(error.response.status) || defaultErrorMsg
    } else {errMsg = "连接到服务器失败"}

    return Promise.reject(errMsg)
  }
)

export default ({url, data = {}, params = {}, ...args}) => {return new Promise((resolve, reject) => {
    axios({
      baseURL,
      url,
      params,
      data: {
        ...data,
        requestName: url.split('/').slice(-1).pop()},
      ...args
    })
      .then(res => resolve(res))
      .catch(err => {console.log(err)
        reject(err)
      })
  })
}

/**
   get 请求:await request({
      method: 'get',
      url: '/user/12345',
      params: {
        name: 'Bob',
        age: 20
      }
    })

  post 请求:await request({
      method: 'post',
      url: '/user/12345',
      data: {
        name: 'Bob',
        age: 20
      }
    })
 */

正文完
 0