Vue中Axios中取消請求及阻止重復請求的方法
更新時間:2022年02月15日 10:09:29 作者:FogDispersed
為了防止用戶在網絡不好或者其他情況下短時間內重復進行接口請求,重復發(fā)送多次請求,本文主要介紹了Vue中Axios中取消請求及阻止重復請求的方法,感興趣的可以了解一下
阻止請求目的:
為了防止用戶在網絡不好或者其他情況下短時間內重復進行接口請求,從而導致前端向后端重復發(fā)送多次請求。
常見情況:
PC端:輸入框搜素,多次請求接口移動端:移動端很容易造成誤操作或多操作請求(移動端沒有點擊延遲)
注意:有Loading遮罩時也有可能發(fā)生重復請求
新建 axios.js 文件
import axios from "axios"; // import router from "../js/router"; // import { Message } from "element-ui"; /** * @description 函數(shù)返回唯一的請求key **/ function getRequestKey(config) { let { method, url, params, data } = config; // axios中取消請求及阻止重復請求的方法 // 參數(shù)相同時阻止重復請求: // return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&"); // 請求方法相同,參數(shù)不同時阻止重復請求 return [method, url].join("&"); } /** * @description 添加請求信息 **/ let pendingRequest = new Map(); function addPendingRequest(config) { // console.log(config.url) let requestKey = getRequestKey(config); config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => { if (!pendingRequest.has(requestKey)) { pendingRequest.set(requestKey, cancel); } }); } /** * @description 取消重復請求 **/ function removePendingRequest(config) { let requestKey = getRequestKey(config); if (pendingRequest.has(requestKey)) { // 如果是重復的請求,則執(zhí)行對應的cancel函數(shù) let cancel = pendingRequest.get(requestKey); cancel(requestKey); // 將前一次重復的請求移除 pendingRequest.delete(requestKey); } } /** * @description 請求攔截器 **/ axios.interceptors.request.use( function (config) { // 檢查是否存在重復請求,若存在則取消已發(fā)的請求 removePendingRequest(config); // 把當前請求信息添加到pendingRequest對象中 addPendingRequest(config); return config; }, function (error) { return Promise.reject(error); } ); /** * @description 響應攔截器 **/ axios.interceptors.response.use( function (response) { // 對響應數(shù)據做點什么 removePendingRequest(response.config); // 該方法是項目中用到 // if (response.data.message == "您沒有獲得授權") { // Message({ // type: "warning", // message: "您沒有獲得授權,請重新登錄", // }); // localStorage.removeItem('token'); // localStorage.removeItem('data'); // router.push({ // name: "login", // }); // } return response; }, function (error) { // 從pendingRequest對象中移除請求 removePendingRequest(error.config || {}); if (axios.isCancel(error)) { console.log("被取消的重復請求:" + error.message); } return Promise.reject(error); } ); export default axios
全局 main.js 引入
import Vue from "vue"; import axios from "./until/axios"; Vue.prototype.$axios = axios;
到此這篇關于Vue中Axios中取消請求及阻止重復請求的方法的文章就介紹到這了,更多相關Axios取消請求及阻止重復請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue使用recorder-core.js實現(xiàn)錄音功能
這篇文章主要介紹了vue如何使用recorder-core.js實現(xiàn)錄音功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07使用vuex緩存數(shù)據并優(yōu)化自己的vuex-cache
這篇文章主要介紹了使用vuex緩存數(shù)據并優(yōu)化自己的vuex-cache,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05vue cli3.x打包后如何修改生成的靜態(tài)資源的目錄和路徑
這篇文章主要介紹了vue cli3.x打包后如何修改生成的靜態(tài)資源的目錄和路徑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04