处理重复请求:没有响应完成的请求,再去请求一个相同的请求,会把之前的请求取消掉
新增一个cancelRequest.js
文件文章来源:https://www.toymoban.com/news/detail-655093.html
import axios from "axios"
const cancelTokens = {}
export const addPending = (config) => {
const requestKey = getRequestKey(config)
if (cancelTokens[requestKey]) {
cancelTokens[requestKey].cancel('cancel request')
}
const source = axios.CancelToken.source()
cancelTokens[requestKey] = source
config.cancelToken = source.token
}
export const deletePending = (res) => {
const requestKey = getRequestKey(res.config)
if (cancelTokens[requestKey]) {
delete cancelTokens[requestKey]
}
}
const getRequestKey = (config = {}) => {
return config.url + config.method + JSON.stringify(config.params, config.data)
}
request.js
文章来源地址https://www.toymoban.com/news/detail-655093.html
import axios from "axios"
import { baseUrl } from "@/config"
import { addPending, deletePending } from "./cancelRequest"
const service = axios.create({
baseURL: baseUrl,
timeout: 100000,
})
service.interceptors.request.use(
config => {
addPending(config)
return config
},
error => {
return Promise.error(error)
}
)
service.interceptors.response.use(
success => {
deletePending(success)
},
error => {
deletePending(error)
}
)
export default service
到了这里,关于Axios使用CancelToken取消重复请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!