typescript封装axios代码
时间: 2023-05-18 14:06:57 浏览: 131
好的,以下是一个简单的 TypeScript 封装 Axios 的代码示例:
```typescript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
class HttpClient {
private readonly instance: AxiosInstance;
constructor(baseURL: string, headers?: Record<string, string>) {
this.instance = axios.create({
baseURL,
headers,
});
this.instance.interceptors.response.use(this.handleSuccess, this.handleError);
}
private handleSuccess(response: AxiosResponse) {
return response.data;
}
private handleError(error: any) {
console.error(error);
return Promise.reject(error);
}
public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
return this.instance.get<T>(url, config);
}
public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
return this.instance.post<T>(url, data, config);
}
public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
return this.instance.put<T>(url, data, config);
}
public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
return this.instance.delete<T>(url, config);
}
}
export default HttpClient;
```
这个类封装了 Axios 的常用 HTTP 方法,可以通过传入 baseURL 和 headers 来创建一个实例。在构造函数中,我们还添加了一个响应拦截器,用于处理成功和失败的响应。
阅读全文