You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

扩展Axios以支持接收URL类型的请求地址

解决方案

1. 扩展Axios类型定义

先在TypeScript中扩展Axios的类型,让get方法支持接收URL对象作为参数。创建一个类型声明文件(比如axios.d.ts):

import axios from 'axios';

declare module 'axios' {
  interface AxiosInstance {
    get<T = any, R = AxiosResponse<T>, D = any>(
      url: URL | string,
      config?: AxiosRequestConfig<D>
    ): Promise<R>;
  }

  interface AxiosStatic {
    get<T = any, R = AxiosResponse<T>, D = any>(
      url: URL | string,
      config?: AxiosRequestConfig<D>
    ): Promise<R>;
  }
}

2. 封装Axios实例实现URL转换

不需要直接继承Axios类,通过包装get方法的方式实现需求,更稳妥:

自定义Axios实例(推荐)

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

const createAxiosWithUrlSupport = (config?: AxiosRequestConfig): AxiosInstance => {
  const instance = axios.create(config);
  const originalGet = instance.get;

  instance.get = async function<T = any, R = AxiosResponse<T>, D = any>(
    url: URL | string,
    config?: AxiosRequestConfig<D>
  ): Promise<R> {
    const urlStr = typeof url === 'object' ? url.toString() : url;
    return originalGet.call(this, urlStr, config);
  };

  return instance;
};

// 使用示例
const api = createAxiosWithUrlSupport();
api.get(new URL('https://example.com/api/data'));

全局扩展Axios(不推荐,易引发副作用)

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

const originalGet = axios.get;

axios.get = async function<T = any, R = AxiosResponse<T>, D = any>(
  url: URL | string,
  config?: AxiosRequestConfig<D>
): Promise<R> {
  const urlStr = typeof url === 'object' ? url.toString() : url;
  return originalGet.call(this, urlStr, config);
};

// 全局使用示例
axios.get(new URL('https://example.com/api/data'));

为何直接继承Axios类无效?

Axios的实例方法(如get)是在实例创建时挂载到原型链上的,直接继承并重写get会因为Axios内部的实例初始化逻辑,导致重载方法无法被正确调用。而通过保存原始方法、替换实例上的get方法的方式,能确保URL转换逻辑被触发。

内容的提问来源于stack exchange,提问作者owittek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 18:50:42