axios在elecrton请求超时处理办法
自己开发的一款elecron批量上传商品工具,在使用的过程中,会偶尔出现请求超时问题,无法获取到数据。
import axios from 'axios'
import { Message } from 'element-ui'
const serves = axios.create({
baseURL: process.env.BASE_API,
timeout: 3000
})
// 设置请求次数,请求间隔
serves.defaults.retry = 4;
serves.defaults.retryDelay = 800;
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
Message.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);
});
});
// 设置请求发送之前的拦截器
serves.interceptors.request.use(config => {
config.headers.action = localStorage.getItem('name')
return config
}, err => Promise.reject(err))
// 将serves抛出去
export default serves
本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。