1、使用场景
(1)后端接口请求超时。
(2)后端接口报错。
(3)弱网状态下,重新请求。
2、实现步骤
axios中的使用
以下代码都是在api.js中进行操作:
(1)先进行axios的配置:
//设置全局的请求次数,请求的间隙
axios.defaults.retry = 3; // 请求次数
axios.defaults.retryDelay = 2000; //请求间隙
(2)设置拦截器
axios.interceptors.response.use((res) => {
// 拦截器配置
if (res.data.code == 400 || res.data.code == 1) {
Toast.fail(res.data.msg)
}
if (res.data.code == 401) {
Toast.fail(res.data.msg)
console.log('go login')
clearInterval(window.checktimer)
localStorage.clear()
router.replace({
path: '/login'
})
return Promise.reject(res)
}
return res // data数据
}, (error) => {
// 请求失败
// Tool.toast('网络异常', 'fail')
// Tool.close()
// return Promise.reject(error)
var config = error.config;
config.retry = 3;
config.retryDelay = 5000;
// 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
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);
});
})