Typescript 封装 Axios拦截器方法实例
目录
- 引言
- 创建 class
- axios.create([config])
- 封装 request(config)通用方法
- 封装-拦截器(单个实例独享)
- 扩展 Http 自定义拦截器
- 封装-拦截器(所有实例共享)
- 封装-拦截器(单个请求独享)
- 装修 Http class
- 返回经过
- request 返回数据结构(DTO)
- 拦截器执行顺序
- 操作场景控制
引言
对 axios 二次封装,更加的可配置化、扩展性更加强大灵活
通过 class 类实现,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'}
});
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;
};
}
封装 request(config)通用方法
/**
* axios#request(config)
* @param {*} config
* @returns {*}
*/
request(config: AxiosRequestConfig) {
return this.axios.request(config)
}
赞 (0)
