解决 axios: “timeout of 5000ms exceeded” 超时的问题

最近遇到一个问题,在我开机后,启动后台服务器登录程序时会报请求超时的问题。网上找了下解决方法,最后成功解决。

首先,我们要查看自己的请求地址是否正确,后端是否正常开启,数据库是否启动;若都正确无误,则继续往下看。

在看以下代码时,大家可以参考我的另一篇博文:vue开发中 axios 的封装

注:我使用的是 0.18.1 版本,0.19.0 版本似乎有问题,见:https://github.com/ly2011/blog/issues/159 中的评论。

具体代码如下: 

import axios from 'axios'
import { BASE_URL } from './http'
import router from '../router'

// create an axios instance
const service = axios.create({
  baseURL: BASE_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})


// 设置请求次数,请求的间隙
service.defaults.retry = 4;
service.defaults.retryDelay = 1000;

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    if (error.response) {
      // console.log('err' + error) // for debug
      switch (error.response.status) {
        case 401:
          // console.log('err status' + error.response.status)
          router.push('/login')
          break
        case 404:
          break
        case 500:
          break
      }
      return Promise.reject(error)
    } else {
      // 处理超时的情况
      let config = error.config
      // If config does not exist or the retry option is not set, reject
      if(!config || !config.retry) return Promise.reject(error)
  
      // 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(error)
      }
  
      // Increase the retry count
      config.__retryCount += 1
  
      // Create new promise to handle exponential backoff
      let backoff = new Promise(function(resolve) {
        setTimeout(function() {
          resolve()
        }, config.retryDelay || 1)
      })
  
      // Return the promise in which recalls axios to retry the request
      return backoff.then(function() {
        return service(config)
      })
    }

  }
)

export default service

当请求超时后,axios 将重新发起请求,请求次数和间隙可以自己设定。这里我创建了一个 axios 实例,所有 api 接口都通过这个实例进行请求。如果你不想这样做,可以像下面这样写:

//在main.js设置全局的请求次数,请求的间隙
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;

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);
    });

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
        return axios(config);
    });
});

参考链接:https://github.com/axios/axios/issues/164

你可能感兴趣的:(vue)