Axios使用

27 阅读1分钟

Axios使用封装

创建基础配置

/**
 * API URL and version
 */
export const API_URL = 'http://xxxxxxxxxxx/api';

/**
 * API version
 */
export const API_VERSION = 'v1';

export const MODEL_API_VERSION = 'v3';

/**
 * API token for authentication
 * TODO: Replace with actual token
 */
export const TOKEN = 'XXXXXX';

/**
 * Configuration ID for API requests
 * TODO: Replace with actual configuration ID
 */
export const CONFIG_ID = {
  author_id: 'XXXXXX',
  workspace_id: 'XXXXXX',
  tenant_id: 'XXXXXX'
}

/**
 * API request timeout in milliseconds
 */
export const TIMEOUT = 10000;

创建Api Service


import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

import { API_URL, TIMEOUT, TOKEN, CONFIG_ID } from '@/configs';

class ApiService {
  private instance: AxiosInstance;

  constructor(baseURL: string) {
    this.instance = axios.create({
      baseURL,
      timeout: TIMEOUT,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    this.setupInterceptors();
  }

  private setupInterceptors() {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // TODO: 添加配置ID到请求参数中
        config.data = {...CONFIG_ID, ...config.data};
        // TODO: 登录后把鉴权token放到 localStorage
        const token = localStorage.getItem('token') || TOKEN;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        return response?.data;
      },
      (error) => {
        // 统一错误处理
        if (error.response?.status === 401) {
          // 处理未授权
          localStorage.removeItem('token');
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }

  // GET 请求(查询数据详情)
  async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.get(url, config);
    return response.data;
  }

  // POST 请求(添加数据或查询列表数据)
  async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.post(url, data, config);
    return response.data;
  }

  // PUT 请求(更新数据)
  async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.put(url, data, config);
    return response.data;
  }

  // DELETE 请求(删除数据)
  async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response: AxiosResponse<T> = await this.instance.delete(url, config);
    return response.data;
  }
}

// 创建实例
export const apiService = new ApiService(process.env.REACT_APP_API_BASE_URL || API_URL);

创建基础服务


import { apiService } from './api-service';
import { API_URL, API_VERSION } from '@/configs';

export class BaseService {
  protected baseURL: string = API_URL;

  protected apiVersion: string = API_VERSION;

  protected serviceName: string = '';

  protected page_size: number = 10;

  protected page_number: number = 1;

  constructor(serviceName: string) {
    this.serviceName = serviceName;
  }

  get serviceURL() {
    return `${this.baseURL}/${this.apiVersion}/${this.serviceName}`;
  }

  public async getPageList<T>(data?: any): Promise<any> {
    const params = {
      page_size: this.page_size,
      page_number: this.page_number,
      ...data,
    };
    const result = await apiService.post<T>(`${this.serviceURL}/page`, params);
    // TODO: 后端返回数据集字段名不一致
    return result?.records;
  }

  public async getList<T>(data?: any): Promise<any> {
    const params = {
      page_size: this.page_size,
      page: this.page_number,
      ...data,
    };
    const result = await apiService.post<T>(`${this.serviceURL}`, params);
    return result?.items;
  }

  public async getDetail<T>(id: string): Promise<any> {
    const result = await apiService.get<T>(`${this.serviceURL}/${id}`);
    return result;
  }

  public async add<T>(data: any): Promise<any> {
    return apiService.post<T>(`${this.serviceURL}`, data);
  }

  public async update<T>(data: any): Promise<any> {
    return apiService.put<T>(`${this.serviceURL}`, data);
  }

  public async delete<T>(id: string): Promise<any> {
    return apiService.delete<T>(`${this.serviceURL}/${id}`);
  }
}

具体使用


class DMService extends BaseService {

  protected page_size: number = 100;
//写自己的逻辑
}

export const dmService = new DMService('kb');