处理重复请求:没有响应完成的请求,再去请求一个相同的请求,会把之前的请求取消掉
新增一个cancelRequest.js
文件
js
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
js
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