import { default as axios, AxiosRequestConfig, Canceler } from 'axios'
import { ElMessageBox, ElLoading } from 'element-plus'
import { Session } from '@/utils/storage'
// ajax
const service = axios.create({
baseURL,
headers: {},
})
// CancelToken 取消请求
const CancelToken = axios.CancelToken
const cancelTokenMap = new Map<RequestConfig, Canceler>()
// CancelToken 的构造函数来创建 cancel token
const createCancelToken = (config: RequestConfig) => {
return new CancelToken(function executor(cancel) {
// executor 函数接收一个 cancel 函数作为参数
cancelTokenMap.set(config, cancel)
})
}
// 删除单个 cancel token
const deleteCancelToken = (config: RequestConfig) => {
cancelTokenMap.delete(config)
}
// 取消所有请求
const abortCancelToken = () => {
for (let cancel of cancelTokenMap.values()) {
cancel('canceled')
}
cancelTokenMap.clear()
}
// 请求前
service.interceptors.request.use(
async (config: any) => {
config.cancelToken = createCancelToken(config)
return config
},
(error: any) => {
return Promise.reject(error)
}
)
// 响应后
service.interceptors.response.use(
(response: any) => {
deleteCancelToken(response.config)
return response.data
},
function (error: any) {
deleteCancelToken(error?.response?.config)
if (response.status == 401 || response.status == 403) {
ElMessageBox.confirm('无权限', 'token过期,请重新登录')
.then(() => {
Session.remove('Token')
history.go()
})
abortCancelToken()
return Promise.reject(error)
}
// 取消请求
if (error.message === 'canceled') {
return Promise.reject(error)
}
return Promise.reject(error)
}
)
网友评论