Vue中Axios中取消请求及阻止重复请求的方法

为了防止用户在网络不好或者其他情况下短时间内重复进行接口请求,重复发送多次请求,本文主要介绍了Vue中Axios中取消请求及阻止重复请求的方法,感兴趣的可以了解一下

阻止请求目的:

为了防止用户在网络不好或者其他情况下短时间内重复进行接口请求,从而导致前端向后端重复发送多次请求。

常见情况:

PC端:输入框搜素,多次请求接口移动端:移动端很容易造成误操作或多操作请求(移动端没有点击延迟)
注意:有Loading遮罩时也有可能发生重复请求

新建 axios.js 文件

在这里插入图片描述

import axios from "axios"; // import router from "../js/router"; // import {  Message } from "element-ui"; /** * @description 函数返回唯一的请求key **/ function getRequestKey(config) { let { method, url, params, data } = config; // axios中取消请求及阻止重复请求的方法 // 参数相同时阻止重复请求: // return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&"); // 请求方法相同,参数不同时阻止重复请求 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)) { // 如果是重复的请求,则执行对应的cancel函数 let cancel = pendingRequest.get(requestKey); cancel(requestKey); // 将前一次重复的请求移除 pendingRequest.delete(requestKey); } } /** * @description 请求拦截器 **/ axios.interceptors.request.use( function (config) { // 检查是否存在重复请求,若存在则取消已发的请求 removePendingRequest(config); // 把当前请求信息添加到pendingRequest对象中 addPendingRequest(config); return config; }, function (error) { return Promise.reject(error); } ); /** * @description 响应拦截器 **/ axios.interceptors.response.use( function (response) { // 对响应数据做点什么 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取消请求及阻止重复请求内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是Vue中Axios中取消请求及阻止重复请求的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Vue.js 教程