处理重复请求:没有响应完成的请求,再去请求一个相同的请求,会把之前的请求取消掉
新增一个cancelRequest.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
- 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
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |