源码
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 67 68 69 70
| import {ElMessage} from "element-plus";
export default function setupRequest(obj) { obj.interceptors.request.use( config => { config.headers['X-Requested-With'] = 'XMLHttpRequest' config.__retryTimes = 2 config.timeout = 5000 return config }, error => { return Promise.reject(error) } )
obj.interceptors.response.use( response => { return response }, error => { let config = error.config if ( (!config || !config.__retryTimes) || (error.response && error.response.status < 500) || (config.__retryCount >= config.__retryTimes) ) { if (!error.response) { ElMessage({ message: '请求失败,请检查网络连接。', type: 'error', duration: 5 * 1000 }) } else if (error.response.status === 419) { ElMessage({ message: '页面已过期,请刷新重试。', type: 'error', duration: 5 * 1000 }) } return Promise.reject(error); }
config.__retryCount = 0 | config.__retryCount config.retryDelay = 500 error.config.__retryCount ++;
const delay = new Promise((resolve) => { setTimeout(() => { resolve(); }, error.config.retryDelay); }); return delay.then(() => { return obj(error.config); }); } )
}
export var baseUrl = 'http://' + window.location.host
|
注意
这里的 __retryCount
的初始化即 config.__retryCount = 0
不能出现在 request
拦截器中,会导致每次的 __retryCount
都被重置,从而导致重试进入死循环。