新建utils/http.ts文件
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
interface HttpConfig extends AxiosRequestConfig {};
class Http {
private http: AxiosInstance;
private baseConfig: AxiosRequestConfig = {
baseURL: import.meta.env.VITE_API_URL,
timeout: 60000
};
constructor(config: HttpConfig) {
this.http = axios.create(Object.assign(config, this.baseConfig));
this.http.interceptors.request.use(this.handleRequest);
this.http.interceptors.response.use(this.handleResponse, this.handleError);
}
public async get<T>(url: string, config?: HttpConfig): Promise<T> {
const response = await this.http.get<T>(url, {
...config
})
return response.data;
}
public async post<T>(url: string, data?: any, config?: HttpConfig): Promise<T> {
const response = await this.http.post<T>(url, data, {
...config
});
return response.data;
}
private handleRequest(config: AxiosRequestConfig): AxiosRequestConfig {
return config;
}
private handleResponse(response: AxiosResponse): AxiosResponse {
let {code,message,data} = response.data;
if (code !== 200) {
console.error(message);
}
return data;
}
private handleError(error: any): Promise<any> {
if (axios.isCancel(error)) {
console.warn('Request canceled:', error.message);
}
return Promise.reject(error);
}
}
export default new Http({});