axios-instance.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import axios, {type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
  2. import {ElMessage} from 'element-plus';
  3. // 自定义配置接口
  4. export interface CustomInstanceConfig extends AxiosRequestConfig {
  5. // 可以添加自定义配置
  6. skipAuth?: boolean; // 是否跳过鉴权
  7. }
  8. // 创建 Axios 实例
  9. const axiosInstance: AxiosInstance = axios.create({
  10. baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  11. timeout: 30000,
  12. headers: {
  13. 'Content-Type': 'application/json',
  14. },
  15. });
  16. // 请求拦截器
  17. axiosInstance.interceptors.request.use(
  18. (config) => {
  19. // 添加 token
  20. const token = localStorage.getItem('token');
  21. if (token) {
  22. config.headers.Authorization = `Bearer ${token}`;
  23. }
  24. return config;
  25. },
  26. (error) => {
  27. return Promise.reject(error);
  28. }
  29. );
  30. // 响应拦截器
  31. axiosInstance.interceptors.response.use(
  32. (response: AxiosResponse) => {
  33. // 根据后端返回格式调整
  34. if (response.data.code !== 0 && response.data.code !== 200) {
  35. if (response.data.message) {
  36. ElMessage.error(response.data.message);
  37. }
  38. return Promise.reject(new Error(response.data.message || '请求失败'));
  39. }
  40. if (response.data.message) {
  41. ElMessage.success(response.data.message);
  42. }
  43. return response.data;
  44. },
  45. (error) => {
  46. // 统一错误处理
  47. if (error.response?.status === 401) {
  48. // 未授权,跳转登录
  49. window.location.href = '/login';
  50. }
  51. return Promise.reject(error);
  52. }
  53. );
  54. // 自定义实例函数(供 Orval 使用)
  55. export const customAxiosInstance = <T>(config: CustomInstanceConfig): Promise<T> => {
  56. return axiosInstance(config);
  57. };
  58. // 也可以导出第二参数形式(如需处理完整响应)
  59. export const customAxiosInstanceWithFullResponse = <T>(
  60. config: CustomInstanceConfig
  61. ): Promise<AxiosResponse<T>> => {
  62. return axiosInstance(config);
  63. };