import axios from 'axios'

const CancelToken = axios.CancelToken
const requestMap = new Map()
let lastUniqueCode = ''

const apiAxios = axios.create({
    baseURL:'/',
    timeout:10000
})

apiAxios.interceptors.request.use(function (config) {
    const uniqueCode = config.method + config.baseURL + config.url
    lastUniqueCode = uniqueCode
    if(requestMap.get(uniqueCode)){
        config.cancelToken = new CancelToken(cancel => cancel('请不要重复提交!'))
    } else {
        config.cancelToken = new CancelToken(cancel => requestMap.set(uniqueCode, cancel))
    }
    return config;
})

apiAxios.interceptors.response.use(function (response) {
    const uniqueCode = response.config.method.toLowerCase() + response.config.baseURL + response.config.url
    if (requestMap.get(uniqueCode)) {
      requestMap.delete(uniqueCode)
    }
    return response.data
}, error => {
    if (error.message!='请不要重复提交!') {
        requestMap.delete(lastUniqueCode)
        //如果api为404时候也需要删除对应UniqueCode
    }
    return Promise.reject(error);
    
})
作者 铁血 汉子 2021年6月18日
2021/09/16/07:39:16pm 2021/6/18/10:50:25
0 180