msidolphin / vue-api-creator

An api manager bases on axios
MIT License
10 stars 1 forks source link

有关于请求超时的解决方案吗? #3

Closed weiweidong1993 closed 4 years ago

weiweidong1993 commented 4 years ago

呜呜呜,快告诉我,不然我就。。。哭给你看

msidolphin commented 4 years ago

@weiweidong1993 你可以自行传入axios实例

import Vue from 'vue'
import ApiCreator from 'vue-api-creator'
import axios from 'axios'

axios.defaults.retry = 4 // 重试次数
axios.defaults.timeout = 500 // 设置超时时间
axios.defaults.retryDelay = 1000 // 重试间隔
// https://github.com/axios/axios/blob/26b06391f831ef98606ec0ed406d2be1742e9850/lib/adapters/xhr.js#L95-L101
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
  var config = err.config
  // If config does not exist or the retry option is not set, reject
  if(!config || !config.retry) return Promise.reject(err)
  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0
  // Check if we've maxed out the total number of retries
  if(config.__retryCount >= config.retry) {
      // Reject with the error
      return Promise.reject(err)
  }
  // Increase the retry count
  config.__retryCount += 1
  // Create new promise to handle exponential backoff
  var backoff = new Promise(function(resolve) {
      setTimeout(function() {
          resolve()
      }, config.retryDelay || 1)
  })
  // 返回axios实例,重试请求
  return backoff.then(function() {
      return axios(config)
  })
})
Vue.use(ApiCreator, {
  axios, // 传入axios实例
 // 略
})
weiweidong1993 commented 4 years ago

好的 谢谢,一定要坚持更新下去啊 项目就靠你了