說明: 參考網上 import axios from 'axios' let service = axios.create({ baseUrl: '', timeout: 10000 }) let pending = []; //聲明一個數組用於存儲每個ajax請求的取消函數和ajax標識 let cancelToken = axios.CancelToken; let removePending = (config) => { for(let p in pending){ if(pending[p].u === config.url + '&' + config.method) { //當前請求在數組中存在時執行函數體 pending[p].f(); //執行取消操作 pending.splice(p, 1); //把這條記錄從數組中移除 } } }
axios.interceptors.request.use(config => {
let str_data = JSON.stringify(config.data || '{}'); // 參數中攜帶cancelHttp,不防止多次請求
if (str_data.indexOf("cancelHttp") > -1) {
httpFlag = false
}else {
removePending(config); //在一個ajax發送前執行一下取消操作
// 這裏的ajax標識我是用請求地址&請求方式拼接的字符串,當然你可以選擇其他的一些方式
config.cancelToken = new cancelToken((c)=>{
pending.push({ u: config.url + '&' + config.method, f: c });
});
}
return config
},error=> {
return Promise.reject(error)
})
let httpFlag = true
axios.interceptors.response.use(response =>{
if (httpFlag) {
removePending(response.config)
}
})