Files
deerflow-code/web-code/lib/api.ts
T
2026-05-28 18:29:37 +08:00

95 lines
2.3 KiB
TypeScript

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
// 创建axios实例
const api: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
api.interceptors.request.use(
(config) => {
// 可以在这里添加token等认证信息
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
api.interceptors.response.use(
(response: AxiosResponse) => {
// 只返回data部分
return response.data;
},
(error) => {
// 统一错误处理
if (error.response) {
// 服务器返回错误状态码
switch (error.response.status) {
case 401:
// 未授权,可跳转到登录页
break;
case 403:
// 禁止访问
break;
case 404:
// 资源不存在
break;
case 500:
// 服务器错误
break;
default:
break;
}
} else if (error.request) {
// 请求已发出但没有收到响应
console.error('网络错误,请检查网络连接');
} else {
// 请求配置出错
console.error('请求配置错误:', error.message);
}
return Promise.reject(error);
}
);
// 封装GET请求
export const get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
return api.get(url, {
params,
...config,
});
};
// 封装POST请求
export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
return api.post(url, data, config);
};
// 封装PUT请求
export const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
return api.put(url, data, config);
};
// 封装DELETE请求
export const del = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
return api.delete(url, {
params,
...config,
});
};
// 封装PATCH请求
export const patch = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
return api.patch(url, data, config);
};
export default api;