【W(wǎng)eb】axios 工具類封裝

Axios 封裝工具類,包含更完善的功能和更清晰的代碼結(jié)構(gòu),提升了可讀性、復(fù)用性和擴(kuò)展性:

關(guān)鍵點(diǎn)

  1. 響應(yīng)類型的細(xì)化
    明確 ApiResponse 類型,使其更具通用性。
  2. 全局配置的抽離
    axios 的默認(rèn)配置集中管理,方便后續(xù)維護(hù)。
  3. 攔截器的增強(qiáng)
    添加更詳細(xì)的錯(cuò)誤處理和日志功能。
  4. 文件上傳的參數(shù)增強(qiáng)
    支持動態(tài)添加額外的表單字段。
  5. 請求方法類型優(yōu)化
    通過 TypeScript 類型定義提高類型安全性。
  6. 取消請求功能
    添加取消請求的功能,便于在某些場景中手動中斷請求。

完整代碼

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import qs from "qs";
import { showToastFail } from "@/utils/my-utils";
import { getUrlParam } from "@/utils";
import { sign } from "@/utils/aes";

// 全局配置
const TIME_OUT = 30 * 1000;
const BASE_URL = process.env.VITE_API_BASE_URL || ""; // 支持環(huán)境變量配置

interface ApiResponse<T = any> {
  code: number;
  message?: string;
  data: T;
  msg?: string;
}

// 初始化 Axios 實(shí)例
const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: BASE_URL,
    timeout: TIME_OUT,
    headers: {
      "Content-Type": "application/json",
    },
    paramsSerializer: params => qs.stringify(params, { arrayFormat: "brackets" }),
  });

  // 設(shè)置攔截器
  setInterceptors(instance);

  return instance;
};

const axiosInstance = createAxiosInstance();

// 請求攔截器
function setInterceptors(instance: AxiosInstance) {
  const { type = "usdt", tgid = "123456" } = getUrlParam();

  // 請求攔截
  instance.interceptors.request.use((config: AxiosRequestConfig) => {
    const params = config.params || {};
    const data = config.data ? queryStringToObject(config.data) : {};

    const headers = {
      "Content-Type": "application/x-www-form-urlencoded",
    };

    config.headers = {
      ...headers,
      ...config.headers,
    };

    return config;
  });

  // 響應(yīng)攔截
  instance.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      const { data } = response;
      if (data.code !== 0) {
        showToastFail(data?.message || data?.msg || "Request failed");
        return Promise.reject(data);
      }
      return Promise.resolve(data);
    },
    (error: any) => {
      const errorMsg = error.response?.data?.message || "Network error occurred";
      showToastFail(errorMsg);
      return Promise.reject(error);
    }
  );
}

// 查詢字符串轉(zhuǎn)換為對象
function queryStringToObject(queryString: string) {
  const params: Record<string, any> = {};
  new URLSearchParams(queryString).forEach((value, key) => {
    params[key] = isNaN(Number(value)) ? value : Number(value);
  });
  return params;
}

// HTTP 工具類
export const http = {
  get<T = any>(url: string, params?: any, headers?: any): Promise<ApiResponse<T>> {
    return axiosInstance({
      url,
      method: "get",
      params,
      headers,
    });
  },

  post<T = any>(url: string, data?: any, headers?: any): Promise<ApiResponse<T>> {
    return axiosInstance({
      url,
      method: "post",
      data: qs.stringify(data),
      headers,
    });
  },

  postJson<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return axiosInstance({
      url,
      method: "post",
      data,
      headers: {
        "Content-Type": "application/json",
      },
    });
  },

  put<T = any>(url: string, data?: any, headers?: any): Promise<ApiResponse<T>> {
    return axiosInstance({
      url,
      method: "put",
      data: qs.stringify(data),
      headers,
    });
  },

  delete<T = any>(url: string, params?: any, headers?: any): Promise<ApiResponse<T>> {
    return axiosInstance({
      url,
      method: "delete",
      params,
      headers,
    });
  },

  uploadFile<T = any>(url: string, file: File, additionalData?: Record<string, any>): Promise<ApiResponse<T>> {
    const formData = new FormData();
    formData.append("file", file);
    if (additionalData) {
      Object.keys(additionalData).forEach(key => formData.append(key, additionalData[key]));
    }

    return axiosInstance({
      url,
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  cancelToken(): { token: any; cancel: () => void } {
    const CancelToken = axios.CancelToken;
    let cancel: () => void;
    const token = new CancelToken(c => {
      cancel = c;
    });
    return { token, cancel };
  },
};

// 導(dǎo)出默認(rèn)實(shí)例
export default http;

調(diào)用示例

普通請求

http.get("/api/users", { page: 1, size: 10 }).then(res => {
  console.log("User data:", res.data);
}).catch(err => {
  console.error("Request error:", err);
});

文件上傳

const file = document.querySelector("input[type='file']").files[0];
http.uploadFile("/api/upload", file, { userId: 123 }).then(res => {
  console.log("Upload success:", res.data);
}).catch(err => {
  console.error("Upload failed:", err);
});

取消請求

const { token, cancel } = http.cancelToken();

http.get("/api/data", {}, { cancelToken: token })
  .then(res => console.log(res))
  .catch(err => console.error("Request canceled or failed:", err));

// 手動取消請求
cancel();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容