import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
export default class ApiClient {
private axiosInstance: AxiosInstance;
constructor(config?: AxiosRequestConfig) {
this.axiosInstance = axios.create(config);
}
public async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response = await this.axiosInstance.get(url, config);
return response.data;
}
public async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
const response = await this.axiosInstance.post(url, data, config);
return response.data;
}
public async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
const response = await this.axiosInstance.put(url, data, config);
return response.data;
}
public async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
const response = await this.axiosInstance.delete(url, config);
return response.data;
}
}
使用
import ApiClient from "../utils/apiClient";
const api = new ApiClient({ baseURL: 'https://api.example.com' });
export default async function getUser() {
return await api.get('/users');
}