方式一:
import axios from 'axios'; axios.defaults.timeout = 5000; axios.defaults.baseURL =''; let pending = []; //聲明一個數組用於存儲每個ajax請求的取消函數和ajax標識 let cancelToken = axios.CancelToken; let removePending = (ever) => { for(let p in pending){ if(pending[p].u === ever.url + '&' + ever.method) { //當當前請求在數組中存在時執行函數體 pending[p].f(); //執行取消操作 pending.splice(p, 1); //把這條記錄從數組中移除 } } } //http request 攔截器 axios.interceptors.request.use( config => { config.data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/x-www-form-urlencoded' } // ------------------------------------------------------------------------------------ removePending(config); //在一個ajax發送前執行一下取消操作 config.cancelToken = new cancelToken((c)=>{ // 這里的ajax標識我是用請求地址&請求方式拼接的字符串,當然你可以選擇其他的一些方式 pending.push({ u: config.url + '&' + config.method, f: c }); }); // ----------------------------------------------------------------------------------------- return config; }, error => { return Promise.reject(err); } ); //http response 攔截器 axios.interceptors.response.use( response => { // ------------------------------------------------------------------------------------------ removePending(res.config); //在一個ajax響應后再執行一下取消操作,把已經完成的請求從pending中移除 // ------------------------------------------------------------------------------------------- if(response.data.errCode ==2){ router.push({ path:"/login", querry:{redirect:router.currentRoute.fullPath}//從哪個頁面跳轉 }) } return response; }, error => { return Promise.reject(error) } )
方式二:
// 正在進行中的請求列表
let reqList = []
/**
* 阻止重復請求
* @param {array} reqList - 請求緩存列表
* @param {string} url - 當前請求地址
* @param {function} cancel - 請求中斷函數
* @param {string} errorMessage - 請求中斷時需要顯示的錯誤信息
*/
const stopRepeatRequest = function (reqList, url, cancel, errorMessage) {
const errorMsg = errorMessage || ''
for (let i = 0; i < reqList.length; i++) {
if (reqList[i] === url) {
cancel(errorMsg)
return
}
}
reqList.push(url)
}
/**
* 允許某個請求可以繼續進行
* @param {array} reqList 全部請求列表
* @param {string} url 請求地址
*/
const allowRequest = function (reqList, url) {
for (let i = 0; i < reqList.length; i++) {
if (reqList[i] === url) {
reqList.splice(i, 1)
break
}
}
}
const service = axios.create()
// 請求攔截器
service.interceptors.request.use(
config => {
let cancel
// 設置cancelToken對象
config.cancelToken = new axios.CancelToken(function(c) {
cancel = c
})
// 阻止重復請求。當上個請求未完成時,相同的請求不會進行
stopRepeatRequest(reqList, config.url, cancel, `${config.url} 請求被中斷`)
return config
},
err => Promise.reject(err)
)
// 響應攔截器
service.interceptors.response.use(
response => {
// 增加延遲,相同請求不得在短時間內重復發送
setTimeout(() => {
allowRequest(reqList, response.config.url)
}, 1000)
// ...請求成功后的后續操作
// successHandler(response)
},
error => {
if (axios.isCancel(thrown)) {
console.log(thrown.message);
} else {
// 增加延遲,相同請求不得在短時間內重復發送
setTimeout(() => {
allowRequest(reqList, error.config.url)
}, 1000)
}
// ...請求失敗后的后續操作
// errorHandler(error)
}
)