首页 前端知识 使用 Typescript 封装 Axios

使用 Typescript 封装 Axios

2024-07-01 23:07:57 前端知识 前端哥 439 179 我要收藏

对 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)
} 

? 在 axios 中,request中的 config 参数与实例化时,axios.create(config)传入的参数是相同的,以下是 axios 方法具体参数

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios.getUri([config]) 

封装-拦截器(单个实例独享)

拦截器的hooks,在请求或响应被 then 或 catch 处理前拦截处理

?在请求中,如携带token、loading动画、header配置...,都是一些公有的逻辑ÿ

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13737.html
标签
评论
发布的文章

读魏书生的心得体会

2024-07-03 14:07:10

jQuery 选择器

2024-05-12 00:05:34

Vue中public/assets目录区别

2024-07-02 23:07:29

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!