Axios使用CancelToken取消重复请求

2023-08-18 08:25:11 浏览数 (1)

处理重复请求:没有响应完成的请求,再去请求一个相同的请求,会把之前的请求取消掉

新增一个cancelRequest.js文件

代码语言:javascript复制
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

代码语言:javascript复制
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

0 人点赞