import axios from 'axios' import type { CancelTokenStatic, AxiosRequestConfig, AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios' import { useGlobalStore } from '@/stores' import { hasOwn, hasOwnDefault } from '@/utils' import { ElMessage } from 'element-plus' /** * @description: 请求配置 * @param {extendHeaders} {[key: string]: string} 扩展请求头用于不满足默认的 Content-Type、token 请求头的情况 * @param {ignoreLoading} boolean 是否忽略 loading 默认 false * @param {token} boolean 是否携带 token 默认 true * @param {ignoreCR} boolean 是否取消请求 默认 false * @param {ignoreCRMsg} string 取消请求的提示信息 默认 Request canceled * @param {contentType} $ContentType 重新定义 Content-Type 默认 json * @param {baseURL} $baseURL baseURL 默认 horizon * @param {timeout} number 超时时间 默认 10000 * @return {_AxiosRequestConfig} **/ interface _AxiosRequestConfig extends AxiosRequestConfig { extendHeaders?: { [key: string]: string } ignoreLoading?: boolean token?: boolean ignoreCR?: boolean ignoreCRMsg?: string } enum ContentType { html = 'text/html', text = 'text/plain', file = 'multipart/form-data', json = 'application/json', form = 'application/x-www-form-urlencoded', stream = 'application/octet-stream', } const Request: AxiosInstance = axios.create() const CancelToken: CancelTokenStatic = axios.CancelToken const source: CancelTokenSource = CancelToken.source() const globalStore = useGlobalStore() Request.interceptors.request.use( (config: InternalAxiosRequestConfig) => { globalStore.setGlobalState('loading', !hasOwnDefault(config, 'ignoreLoading', true)) config.baseURL = hasOwnDefault(config, 'baseURL', '/api') config.headers = { ...config.headers, ...{ 'Content-Type': ContentType[hasOwnDefault(config, 'Content-Type', 'json')], }, ...hasOwnDefault(config, 'extendHeaders', {}), } hasOwnDefault(config, 'token', true) && (config.headers.token = globalStore.token) config.data = config.data || {} config.params = config.params || {} config.timeout = hasOwnDefault(config, 'timeout', 10000) config.cancelToken = source.token config.withCredentials = true hasOwnDefault(config, 'ignoreCR', false) && source.cancel(hasOwnDefault(config, 'ignoreCRMsg', 'Request canceled')) return config }, (error: AxiosError) => { return Promise.reject(error) } ) Request.interceptors.response.use( (response: AxiosResponse) => { globalStore.setGlobalState('loading', false) const { data, status } = response let obj = { ...data } if (!hasOwn(data, 'status')) obj.status = status return obj }, (error: AxiosError) => { globalStore.setGlobalState('loading', false) ElMessage.error(error.message) return Promise.reject(error) } ) export default (config?: _AxiosRequestConfig) => Request(config) 修改代码,使其能够批量取消请求
时间: 2023-12-18 12:05:26 浏览: 125
你可以在创建 axios 实例时添加一个 cancelToken 选项,并使用相同的 cancelToken 对象来取消多个请求。具体步骤如下:
1. 定义一个 cancelToken 对象
```typescript
const CancelToken: CancelTokenStatic = axios.CancelToken
const source: CancelTokenSource = CancelToken.source()
```
2. 将 cancelToken 对象传递给所有请求的 config 中
```typescript
config.cancelToken = source.token
```
3. 当需要取消请求时,调用 source.cancel()
```typescript
source.cancel('取消请求')
```
完整代码如下:
```typescript
import axios from 'axios'
import type {
CancelTokenStatic,
AxiosRequestConfig,
AxiosInstance,
AxiosError,
InternalAxiosRequestConfig,
AxiosResponse,
CancelTokenSource,
} from 'axios'
import { useGlobalStore } from '@/stores'
import { hasOwn, hasOwnDefault } from '@/utils'
import { ElMessage } from 'element-plus'
/**
* @description: 请求配置
* @param {extendHeaders} {[key: string]: string} 扩展请求头用于不满足默认的 Content-Type、token 请求头的情况
* @param {ignoreLoading} boolean 是否忽略 loading 默认 false
* @param {token} boolean 是否携带 token 默认 true
* @param {ignoreCR} boolean 是否取消请求 默认 false
* @param {ignoreCRMsg} string 取消请求的提示信息 默认 Request canceled
* @param {contentType} $ContentType 重新定义 Content-Type 默认 json
* @param {baseURL} $baseURL baseURL 默认 horizon
* @param {timeout} number 超时时间 默认 10000
* @return {_AxiosRequestConfig}
**/
interface _AxiosRequestConfig extends AxiosRequestConfig {
extendHeaders?: { [key: string]: string }
ignoreLoading?: boolean
token?: boolean
ignoreCR?: boolean
ignoreCRMsg?: string
}
enum ContentType {
html = 'text/html',
text = 'text/plain',
file = 'multipart/form-data',
json = 'application/json',
form = 'application/x-www-form-urlencoded',
stream = 'application/octet-stream',
}
const Request: AxiosInstance = axios.create()
const CancelToken: CancelTokenStatic = axios.CancelToken
const source: CancelTokenSource = CancelToken.source()
const globalStore = useGlobalStore()
Request.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
globalStore.setGlobalState('loading', !hasOwnDefault(config, 'ignoreLoading', true))
config.baseURL = hasOwnDefault(config, 'baseURL', '/api')
config.headers = {
...config.headers,
...{
'Content-Type': ContentType[hasOwnDefault(config, 'Content-Type', 'json')],
},
...hasOwnDefault(config, 'extendHeaders', {}),
}
hasOwnDefault(config, 'token', true) && (config.headers.token = globalStore.token)
config.data = config.data || {}
config.params = config.params || {}
config.timeout = hasOwnDefault(config, 'timeout', 10000)
config.cancelToken = source.token // 将 cancelToken 对象传递给请求的 config
config.withCredentials = true
hasOwnDefault(config, 'ignoreCR', false) && source.cancel(hasOwnDefault(config, 'ignoreCRMsg', 'Request canceled')) // 当需要取消请求时,调用 source.cancel()
return config
},
(error: AxiosError) => {
return Promise.reject(error)
}
)
Request.interceptors.response.use(
(response: AxiosResponse) => {
globalStore.setGlobalState('loading', false)
const { data, status } = response
let obj = { ...data }
if (!hasOwn(data, 'status')) obj.status = status
return obj
},
(error: AxiosError) => {
globalStore.setGlobalState('loading', false)
ElMessage.error(error.message)
return Promise.reject(error)
}
)
export default (config?: _AxiosRequestConfig) => Request(config)
```
阅读全文