vue项目中对axios的二次封装

近来在使用vue重构公司m站时,使用了axios来进行数据的请求,由于项目的需要,对axios进行了二次封装,点击进入axios

//引入axios
import axios from 'axios'

let cancel ,promiseArr = {}
const CancelToken = axios.CancelToken;
//请求拦截器
axios.interceptors.request.use(config => {
    //发起请求时,取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
        promiseArr[config.url]('操作取消')
        promiseArr[config.url] = cancel
    } else {
        promiseArr[config.url] = cancel
    }
      return config
}, error => {
    return Promise.reject(error)
})

//响应拦截器
axios.interceptors.response.use(response => {
    return response
}, error => {
    return Promise.resolve(error.response)
})

axios.defaults.baseURL = '/api'
//设置默认请求头
axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest'
}
axios.defaults.timeout = 10000

export default {
  //get请求
    get (url,param) {
      return new Promise((resolve,reject) => {
        axios({
          method: 'get',
          url,
          params: param,
          cancelToken: new CancelToken(c => {
            cancel = c
          })
        }).then(res => {
          resolve(res)
        })
      })
    },
  //post请求
    post (url,param) {
      return new Promise((resolve,reject) => {
        axios({
          method: 'post',
          url,
          data: param,
          cancelToken: new CancelToken(c => {
            cancel = c
          })
        }).then(res => {
          resolve(res)
        })
      })
     }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

说明

  1. 为防止发起请求时,当前正在进行的相同请求,在请求拦截器中加入了hash判断,将相同请求url拦截
  2. 将axios中get,post公共配置抽离出来
    axios.defaults.baseURL = '/api'
    //设置默认请求头
    axios.defaults.headers = {
        'X-Requested-With': 'XMLHttpRequest'
    }
    axios.defaults.timeout = 10000
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  3. get,post请求的封装可能你会问,这里的axios返回的就是promise对象,为什么还要再次对get,post封装一次promise.因为我这边的话,在开发中使用async await会出现数据请求失败的情况,报的错就是返回的不是promise对象。(ps:可async await返回的就是promise呀,这个问题后续再搞一下)就直接return了一个promise对象,以避免上面的错误。下面是请求接口的一个例子
import req from '../api/requestType'
/**
 * 拼团详情
 */
export const groupDetail = param => {
    return req.get('/RestHome/GroupDetail',param)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

下面是数据的获取

async getData() {
    const params = {
        TopCataID: 0,
        pageNumber: this.pageNumber,
        pageSize: this.pageSize
    }
    const res = await groupList(params)
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

到这里我们就简单的封装了一下适合自己项目的axios

猜你喜欢

转载自blog.csdn.net/zhang__ao/article/details/80610127