request.ts 3.56 KB
/**
 * Axios 请求封装
 */

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { getToken, clearAuth } from './auth';

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加 token
    const token = getToken();
    if (token && config.headers) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }

    return config;
  },
  (error: AxiosError) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;

    // 根据实际后端接口规范调整
    // 假设后端返回格式: { code: number, data: any, message: string }
    if (res.code !== undefined && res.code !== 200 && res.code !== 0) {
      console.error('接口错误:', res.message || '未知错误');

      // 401: 未授权
      if (res.code === 401) {
        handleUnauthorized();
      }

      // 403: 无权限
      if (res.code === 403) {
        console.error('无权限访问');
      }

      return Promise.reject(new Error(res.message || '接口请求失败'));
    }

    return res;
  },
  (error: AxiosError) => {
    console.error('响应错误:', error);

    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 401:
          handleUnauthorized();
          break;
        case 403:
          console.error('无权限访问');
          break;
        case 404:
          console.error('请求的资源不存在');
          break;
        case 500:
          console.error('服务器内部错误');
          break;
        default:
          console.error('请求失败:', data);
      }
    } else if (error.request) {
      console.error('网络错误,请检查网络连接');
    } else {
      console.error('请求配置错误:', error.message);
    }

    return Promise.reject(error);
  }
);

/**
 * 处理未授权
 */
const handleUnauthorized = () => {
  console.warn('登录已过期,请重新登录');
  clearAuth();
  
  // 跳转到登录页
  if (window.location.pathname !== '/login') {
    window.location.href = '/login';
  }
};

/**
 * 通用请求方法
 */
export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  return service.request(config);
};

/**
 * GET 请求
 */
export const get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.get(url, { params, ...config });
};

/**
 * POST 请求
 */
export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.post(url, data, config);
};

/**
 * PUT 请求
 */
export const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.put(url, data, config);
};

/**
 * DELETE 请求
 */
export const del = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.delete(url, { params, ...config });
};

/**
 * PATCH 请求
 */
export const patch = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.patch(url, data, config);
};

export default service;