import axios from 'axios'; import type { AxiosInstance } from 'axios'; import apiHost from 'utils/uri'; import type { RequestInterceptors, RequestConfig } from './requestType'; class RequestApi { instance: AxiosInstance; reqConfig: RequestConfig; interceptors?: RequestInterceptors; constructor(config: RequestConfig) { this.reqConfig = config; // 创建axios实例 this.instance = axios.create(config); this.interceptors = config.interceptors; // 使用拦截器 // 1.从config中取出的拦截器是对应的实例的拦截器 this.instance.interceptors.request.use( this.interceptors?.requestInterceptor, this.interceptors?.requestInterceptorCatch, ); this.instance.interceptors.response.use( this.interceptors?.responseInterceptor, this.interceptors?.responseInterceptorCatch, ); // 2.添加所有的实例都有的拦截器 this.instance.interceptors.request.use( (reqConfig: any) => reqConfig, (err: any) => Promise.reject(err), ); this.instance.interceptors.response.use( (res: any) => { const { data, status } = res; // 相应成功 if (status === 200) { return data; } return Promise.reject(res); }, (err: any) => Promise.reject(err), ); } public request(config: RequestConfig): Promise { return new Promise((resolve, reject) => { // 1.单个请求对请求config的处理 let reqConfig = config; if (config.interceptors?.requestInterceptor) { reqConfig = config.interceptors.requestInterceptor(config); } this.instance .request(reqConfig) .then((res: any) => { // 1.单个请求对数据的处理 let data = res; if (reqConfig.interceptors?.responseInterceptor) { data = reqConfig.interceptors.responseInterceptor(res); } // 3.将结果resolve返回出去 resolve(data); }).catch((err: any) => { reject(err); }); }); } public get(config: RequestConfig): Promise { return this.request({ ...config, method: 'GET' }); } public post(config: RequestConfig): Promise { return this.request({ ...config, method: 'POST' }); } } const requestInstance = new RequestApi({ baseURL: apiHost.BASE_URL, timeout: 20000, interceptors: { requestInterceptor: (config) => config, requestInterceptorCatch: (err) => err, responseInterceptor: (res) => res, responseInterceptorCatch: (err) => err, }, }); export { requestInstance, RequestApi };