const config = { method, url, ...param, ...axiosConfig } as PureHttpRequestConfig;
时间: 2024-02-15 09:41:20 浏览: 235
这段代码是使用 TypeScript 编写的,其中 `config` 是一个对象,包含了请求的各种参数,例如请求方法 `method`、请求的 URL `url`、请求参数 `param` 和 Axios 的配置项 `axiosConfig`。`...` 是 ES6 中的扩展运算符,它可以将一个对象展开成多个对象,方便地进行对象合并。`as` 则是 TypeScript 中的类型断言,用于将一个对象断言为某个类型。在这里,`config` 被断言为 `PureHttpRequestConfig` 类型,这是一个自定义的类型,可能是继承自 Axios 的 `AxiosRequestConfig` 类型。
相关问题
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', } interface PendingRequest { url?: string cancel: () => void } const Request: AxiosInstance = axios.create() const CancelToken: CancelTokenStatic = axios.CancelToken const source: CancelTokenSource = CancelToken.source() const pendingRequests: Map<string, PendingRequest> = new Map() 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 = config.cancelToken || new CancelToken(cancel => { const url = config.url || '' if (!pendingRequests.has(url)) { pendingRequests.set(url, { cancel }) } }) hasOwnDefault(config, 'ignoreCR', false) && config.cancelToken!.promise.catch(reason => { ElMessage.warning(hasOwnDefault(config, 'ignoreCRMsg', 'Request canceled')) throw reason }) console.log(pendingRequests) return config }, (error: AxiosError) => { return Promise.reject(error) } ) Request.interceptors.response.use( (response: AxiosResponse) => { globalStore.setGlobalState('loading', false) return response.data }, (error: AxiosError) => { globalStore.setGlobalState('loading', false) const url = error.config.url || '' const pendingRequest = pendingRequests.get(url) if (pendingRequest) { pendingRequest.cancel() pendingRequests.delete(url) } ElMessage.error(error.message) return Promise.reject(error) } ) export default (config?: _AxiosRequestConfig) => Request(config) 根据这段代码给出例子
假设你要发送一个 GET 请求,请求的 URL 是 `https://example.com/api/data`,并且带上一个参数 `id`,值为 123。你可以这样调用:
```js
import Request, { ContentType } from '@/utils/request'
const data = {
id: 123
}
Request({
url: '/data',
method: 'get',
params: data,
headers: {
'Content-Type': ContentType.json
}
}).then(response => {
console.log(response)
}).catch(error => {
console.error(error)
})
```
这个例子中,我们使用了自定义的 `ContentType` 枚举来指定请求头的 Content-Type。同时,我们在请求中带上了一个参数 `id`,值为 123。最终请求的 URL 为 `/data?id=123`。请求成功时,我们会在控制台输出返回的数据;请求失败时,我们会在控制台输出错误信息。
import type { AxiosRequestConfig, Canceler } from 'axios'; import axios from 'axios'; import { isFunction } from '/@/utils/is'; // Used to store the identification and cancellation function of each request let pendingMap = new Map<string, Canceler>(); export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&'); export class AxiosCanceler { /** * Add request * @param {Object} config */ addPending(config: AxiosRequestConfig) { this.removePending(config); const url = getPendingUrl(config); config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => { if (!pendingMap.has(url)) { // If there is no current request in pending, add it pendingMap.set(url, cancel); } }); } /** * @description: Clear all pending */ removeAllPending() { pendingMap.forEach((cancel) => { cancel && isFunction(cancel) && cancel(); }); pendingMap.clear(); } /** * Removal request * @param {Object} config */ removePending(config: AxiosRequestConfig) { const url = getPendingUrl(config); if (pendingMap.has(url)) { // If there is a current request identifier in pending, // the current request needs to be cancelled and removed const cancel = pendingMap.get(url); cancel && cancel(url); pendingMap.delete(url); } } /** * @description: reset */ reset(): void { pendingMap = new Map<string, Canceler>(); } } 这是做什么的
这段代码是一个用于管理取消 Axios 请求的辅助工具类。它包含了以下功能:
1. `addPending(config: AxiosRequestConfig)`: 添加请求到待取消列表中。它会根据请求的方法和 URL 生成一个唯一的标识,并将该标识和取消函数存储在 `pendingMap` 中。
2. `removeAllPending()`: 清除所有待取消的请求。它会遍历 `pendingMap` 中的所有取消函数,并执行它们,然后清空 `pendingMap`。
3. `removePending(config: AxiosRequestConfig)`: 从待取消列表中移除指定的请求。它会根据请求的方法和 URL 生成标识,并从 `pendingMap` 中获取对应的取消函数,然后执行该函数并将其从 `pendingMap` 中删除。
4. `reset()`: 重置待取消列表。它会将 `pendingMap` 重置为空的 Map。
这个工具类的主要作用是在发送请求之前添加请求到待取消列表中,然后根据需要进行取消或清除请求。这在处理页面跳转或组件卸载时非常有用,可以避免因为未完成的请求导致的问题。
阅读全文