axios 重複點擊利用CancelToken阻止請求屢次發送

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) } )
相關文章
相關標籤/搜索