1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'; import { type HttpClientConfig } from './httpClientConfig';
class odinAxios { private instance: AxiosInstance; private requestInterceptor?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
constructor(httpClientConfig: HttpClientConfig) { this.instance = axios.create({ baseURL: httpClientConfig.baseURL, timeout: httpClientConfig.timeout, headers: { 'Content-Type': 'application/json', }, });
this.requestInterceptor = httpClientConfig.requestInterceptor;
this.instance.interceptors.request.use( (config: InternalAxiosRequestConfig) => { if (httpClientConfig.token != null) { config.headers.Authorization = `Bearer ${httpClientConfig.token}`; }
if (this.requestInterceptor) { return this.requestInterceptor(config); }
return config; }, (error: AxiosError) => { return Promise.reject(error); } );
this.instance.interceptors.response.use( (response: AxiosResponse<any, any>) => { if (httpClientConfig.responseInterceptor) { return httpClientConfig.responseInterceptor(response); } if (response.data.code !== 200) { return Promise.reject(response.data); } return response.data; }, (error: AxiosError) => { if (httpClientConfig.errorInterceptor) { return httpClientConfig.errorInterceptor(error); } if (error.response) { switch (error.response.status) { case 401: console.error('未授权,请重新登录'); break; case 404: console.error('请求的资源不存在'); break; case 500: console.error('服务器内部错误'); break; default: console.error('请求失败'); } } else { console.error('网络错误,请检查网络连接'); } return Promise.reject(error); } ); }
public get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T, any>> { return this.instance.get<T>(url, config); }
public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T, any>> { return this.instance.post<T>(url, data, config); }
public put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T, any>> { return this.instance.put<T>(url, data, config); }
public delete<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T, any>> { return this.instance.delete<T>(url, config); } }
export default odinAxios;
|