赞
踩
对 axios 二次封装,更加的可配置化、扩展性更加强大灵活
通过 class 类实现,class 具备更强封装性(
封装、继承、多态
),通过实例化类传入自定义的配置
严格要求实例化时传入的配置,拥有更好的代码提示
/** * @param {AxiosInstance} axios实例类型 * @param {AxiosRequestConfig} axios配置项类型 */ import type { AxiosInstance, AxiosRequestConfig } from 'axios' class Http { axios: AxiosInstance constructor(config: AxiosRequestConfig) { // 创建一个实例 axios.create([config]) this.axios = axios.create(config) } } // 每实例化一个 axios 时,都是不同的 axios 示例,互不干扰 new Http({ baseURL:'qq.com'; timeout:60 * 1 }); new Http({ baseURL:'web.com' });
axios.create([config])
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
- 1
- 2
- 3
- 4
- 5
AxiosRequestConfig 的类型注解
export interface AxiosRequestConfig<D = any> { url?: string; method?: Method | string; baseURL?: string; transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; headers?: AxiosRequestHeaders; params?: any; paramsSerializer?: (params: any) => string; data?: D; timeout?: number; timeoutErrorMessage?: string; withCredentials?: boolean; adapter?: AxiosAdapter; auth?: AxiosBasicCredentials; responseType?: ResponseType; responseEncoding?: responseEncoding | string; xsrfCookieName?: string; xsrfHeaderName?: string; onUploadProgress?: (progressEvent: any) => void; onDownloadProgress?: (progressEvent: any) => void; maxContentLength?: number; validateStatus?: ((status: number) => boolean) | null; maxBodyLength?: number; maxRedirects?: number; beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void; socketPath?: string | null; httpAgent?: any; httpsAgent?: any; proxy?: AxiosProxyConfig | false; cancelToken?: CancelToken; decompress?: boolean; transitional?: TransitionalOptions; signal?: AbortSignal; insecureHTTPParser?: boolean; env?: { FormData?: new (...args: any[]) => object;}; }
/**
* axios#request(config)
* @param {*} config
* @returns {*}
*/
request(config: AxiosRequestConfig) {
return this.axios.request(config)
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/299726
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。