首页
/ Axios API 参考:实例、类、工具函数与常量的完整使用指南

Axios API 参考:实例、类、工具函数与常量的完整使用指南

2026-09-05 15:25:39作者:庞眉杨Will

Axios 包对外暴露了一组稳定的公共 API:默认实例与 Axios 类负责发起 HTTP 请求,AxiosError / CanceledError 体系负责错误与取消语义,AxiosHeaders 负责请求/响应头的管理,而 toFormDatamergeConfiggetAdapterHttpStatusCode 等工具函数则覆盖表单构造、配置合并、适配器选择与状态码常量等高频场景。本篇以当前仓库的 API 参考文档为骨架,逐一说明每个导出项的签名、参数与用法,并结合 lib/axios.js 等源码给出其真实实现位置与行为细节,读完后可在项目中准确地引用、组合这些 API。

所有公共 API 都受到 axios 语义化版本(SemVer)承诺的保护:可以信赖这些函数与类在后续版本中保持稳定,除非发生主版本号变更。

实例:默认导出的 axios 对象

实例 axios 是发起 HTTP 请求时实际使用的核心对象。它本质上是一个工厂函数:调用 createInstance() 会创建一个新的 Axios 类实例,并把 Axios.prototype.request 绑定为该实例本身,使 axios(url, config) 这种类 fetch 的写法可以直接发起请求。axios 上的各种请求方法(getpost 等)即文档中「请求方法别名」一节所描述的内容。

源码中这一过程非常清晰,见 lib/axios.js

// Create an instance of Axios
function createInstance(defaultConfig) {
  const context = new Axios(defaultConfig);
  const instance = bind(Axios.prototype.request, context);

  // Copy axios.prototype to instance
  utils.extend(instance, Axios.prototype, context, { allOwnKeys: true });

  // Copy context to instance
  utils.extend(instance, context, null, { allOwnKeys: true });

  // Factory for creating new instances
  instance.create = function create(instanceConfig) {
    return createInstance(mergeConfig(defaultConfig, instanceConfig));
  };

  return instance;
}

// Create the default instance to be exported
const axios = createInstance(defaults);

也就是说,默认导出的 axios 是用 lib/defaults/index.js 中的默认配置创建出来的实例;而 axios.create(instanceConfig) 会把传入配置与默认配置通过 mergeConfig 合并后派生出新实例。此外,源码还把大量公共 API 挂载到实例上,例如 lib/axios.js 中的:

// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;

// Expose AxiosError class
axios.AxiosError = AxiosError;

// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

axios.spread = spread;
axios.isAxiosError = isAxiosError;
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders;
axios.formToJSON = (thing) => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode;

因此在实际使用中,axios.AxiosErroraxios.isCancelaxios.mergeConfig 等成员与具名导入(import { mergeConfig } from 'axios')指向的是同一份实现。

TypeScript 请求类型

公共的请求相关类型使用分离的泛型来区分「请求体数据」与「查询参数」:

AxiosRequestConfig<D = any, P = any>
RawAxiosRequestConfig<D = any, P = any>
InternalAxiosRequestConfig<D = any, P = any>
AxiosDefaults<D = any, P = any>
CreateAxiosDefaults<D = any, P = any>

AxiosResponse<T = any, D = any, H = {}, P = any>
AxiosPromise<T = any, D = any, P = any>
AxiosError<T = unknown, D = any, P = any>
CanceledError<T, D = any, P = any>

其中 D 是请求体(data)的类型,P 是查询参数(params)的类型。AxiosResponseAxiosPromise、错误类型、默认值类型、可调用实例、请求别名、适配器以及 mergeConfig() 都会在配置中同时保留 DP 两个泛型;自定义参数序列化器(paramsSerializer)也能拿到同样的 P 类型。

请求方法采用泛型顺序 <T, R, D, P>,把 P 放在最后是为了保持既有显式泛型实参的兼容性。当没有显式指定响应类型 R 时,默认的 AxiosResponse 会把 DP 保留在 response.config 中;显式指定 R 则继续控制 resolve 出来的值。数据与参数泛型默认值均为 any,用于维持向后兼容。类型声明的完整定义位于 index.d.tsindex.d.cts,可按需查阅。

Axios

Axios 类是发起 HTTP 请求的主要入口。它是创建 Axios 实例的基础,实例上拥有一整套发起请求的方法(即请求方法别名)。

constructor

创建一个新的 Axios 实例,接受一个可选的配置对象作为默认配置:

constructor(instanceConfig?: AxiosRequestConfig);

lib/core/Axios.js 可以看到构造器的实现非常轻量:

class Axios {
  constructor(instanceConfig) {
    this.defaults = instanceConfig || {};
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager(),
    };
  }
  // ...
}

即实例只持有两份状态:默认配置 defaults 和请求/响应两个拦截器管理器 interceptorsaxios.create() 的默认配置即通过这里传入。

request

request 负责请求的调用与响应的解析,是发起 HTTP 请求的主方法。它接受一个配置对象,返回一个在响应对象上 resolve 的 Promise:

request<T, R, D, P>(config: AxiosRequestConfig<D, P>): Promise<R>;

源码实现上,request 是一个异步包装层,真正的执行逻辑在 _request 中(见 lib/core/Axios.js):

async request(configOrUrl, config) {
  try {
    return await this._request(configOrUrl, config);
  } catch (err) {
    // 为抛出的 Error 补全/拼合 stack 信息后重新抛出
    throw err;
  }
}

_request(configOrUrl, config) {
  // Allow for axios('example/url'[, config]) a la fetch API
  if (typeof configOrUrl === 'string') {
    config = config || {};
    config.url = configOrUrl;
  } else {
    config = configOrUrl || {};
  }

  config = mergeConfig(this.defaults, config);
  // ...
}

几个值得注意的行为:

  • 支持 axios('example/url'[, config]) 这种类 fetch 的字符串首参调用;
  • 每次请求都会先用 mergeConfig(this.defaults, config) 把实例默认配置与单次请求配置合并,请求配置优先生效;
  • 异步错误在重新抛出前会尝试补全 stack,便于在浏览器中定位错误来源。

请求别名(delete/get/head/optionspost/put/patch/query 及各 xxxForm 变体)也是在类定义之后统一挂到 Axios.prototype 上的,见 lib/core/Axios.js

CancelToken(已在 AbortController 面前被标记为废弃)

CancelToken 类最早基于 tc39/proposal-cancelable-promises 提案,用于创建一个可以取消 HTTP 请求的 token。该类自 0.22.0 起已被标记为废弃,官方推荐改用标准 AbortController API,并将在未来的版本中移除。

从源码结构看,它目前仍被导出,主要是为了向前兼容;官方强烈不建议在新项目中使用,下面列出的遗留互操作 helper 仅面向既有代码。其遗留方法仍保留原有类型以便存量集成:

subscribe(listener: (cancel: Cancel | any) => void): void;
unsubscribe(listener: (cancel: Cancel | any) => void): void;
toAbortSignal(): AbortSignal;

其中 toAbortSignal() 提供了从旧 token 桥接到标准 AbortSignal 的途径。实现位于 lib/cancel/CancelToken.js;新项目请直接使用 new AbortController() 并把 signal 传给请求配置。

函数与错误类

AxiosError

AxiosError 是 HTTP 请求失败时被抛出的错误类。它继承自 Error,并在错误对象上附加了与本次请求相关的额外属性。

constructor

创建一个新的 AxiosError 实例,构造参数依次为:可选的消息、错误码、配置、请求对象与响应对象。

constructor(message?: string, code?: string, config?: InternalAxiosRequestConfig<D, P>, request?: any, response?: AxiosResponse<T, D, {}, P>);

源码实现(lib/core/AxiosError.js)中可以看到属性的写入逻辑:

constructor(message, code, config, request, response) {
  super(message);
  // ...(message 被设置为可枚举以保持向后兼容)
  this.name = 'AxiosError';
  this.isAxiosError = true;
  code && (this.code = code);
  config && (this.config = config);
  request && (this.request = request);
  if (response) {
    this.response = response;
    this.status = response.status;
  }
}

也就是说 status 来自 response.statusisAxiosError: trueisAxiosError() 判定的依据。

properties

AxiosError 提供以下属性:

// 配置实例。
config?: InternalAxiosRequestConfig<D, P>;

// 错误码。
code?: string;

// 请求实例。
request?: any;

// 响应实例。
response?: AxiosResponse<T, D, {}, P>;

// 指示该错误是否为 AxiosError 的布尔值。
isAxiosError: boolean;

// 错误对应的 HTTP 状态码。
status?: number;

// 将错误转换为 JSON 对象的辅助方法。
toJSON: () => object;

// 错误成因。
cause?: Error;

补充两点源码级细节:

  • toJSON()lib/core/AxiosError.js)输出包含 messagenameconfigcodestatusstack 等字段的快照;当请求配置中带有非空的 redact 数组时,快照中同名(不区分大小写、任意深度)的键值会被替换为 [REDACTED ****],可用于避免把凭据等敏感配置序列化进日志。
  • 静态成员中定义了一组常见错误码常量,如 ECONNABORTEDETIMEDOUTECONNREFUSEDERR_NETWORKERR_BAD_RESPONSEERR_CANCELEDERR_NOT_SUPPORT 等(lib/core/AxiosError.js),可直接用于比较 error.code

AxiosHeaders

AxiosHeaders 是一个用于管理 HTTP 头的工具类,提供增加、删除、读取请求头等操作方法。以下仅列出核心方法,完整方法列表请参阅类型声明文件 index.d.ts

constructor

创建一个新的 AxiosHeaders 实例,可选传入一个头对象作为初始值:

constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);

set

向头对象中添加一个或多个头。空白或仅由空格组成的头名称会被忽略。

set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
set(headers?: Iterable<[string, AxiosHeaderValue]>, rewrite?: boolean): AxiosHeaders;

lib/core/AxiosHeaders.js 的实现看,set 支持四种输入形态:单个头名+值、普通对象/AxiosHeaders 实例、多行头字符串(内部走 parseHeaders 解析)以及可迭代的键值对数组;头名称在内部统一做 trim + toLowerCase 归一化后查找,因此 Content-typecontent-type 指向同一项。rewrite === true 时会无条件覆盖同名头的既有值。

get

从头对象中读取一个头:

get(headerName: string, parser: typeof AxiosHeaders.parseParameters): AxiosHeaderParameters;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;

第二个参数可以传入不同的解析器。传入 AxiosHeaders.parseParameters 时,会把 HTTP 参数解析为一个带 null 原型的强化映射(避免原型污染):

const headers = new AxiosHeaders({
  'Content-Type': 'multipart/form-data; boundary="a,b"',
});

console.log({
  ...headers.get('Content-Type', AxiosHeaders.parseParameters),
});
// { boundary: 'a,b' }

参数名不区分大小写。从 lib/core/AxiosHeaders.jsparseParameters 实现可以确认其解析细节:会去掉带引号字符串的定界符、解码引号与转义反斜杠、保留引号内的逗号与分号、仅裁剪 RFC 定义的无引号值两侧可选空白(OWS),并且显式跳过 __proto__constructorprototype 三个危险参数名。而 get(name, true) 仍是旧版的 token 化解析器(parseTokenslib/core/AxiosHeaders.js),两者行为有差异,新代码应优先使用 parseParameters

has

检查某个头是否存在于头对象中:

has(header: string, matcher?: AxiosHeaderMatcher): boolean;

delete

从头对象中删除一个或多个头(header 可传字符串或字符串数组):

delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;

clear

清除头对象中的所有头:

clear(matcher?: AxiosHeaderMatcher): boolean;

normalize

归一化头对象(把重复/大小写不一致的同名头合并,formattrue 时同时把头名格式化为首字母大写形式,见 lib/core/AxiosHeaders.js):

normalize(format: boolean): AxiosHeaders;

concat

拼接多个头对象(静态 concat 会以第一个参数为基础依次 set 后续目标,lib/core/AxiosHeaders.js):

concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;

toJSON

把头对象转换为普通 JSON 对象:

toJSON(asStrings: true): Record<string, string>;
toJSON(asStrings?: false): Record<string, string | string[]>;

asStringstrue 时,数组值会用 ', ' 连接为字符串(例如多个 Set-Cookie)。

toString

返回一个不带 CRLF 的 HTTP 头块,每行一个 名称: 值 对:

toString(): string;
// 源码实现:Object.entries(this.toJSON()) 逐行拼接
return Object.entries(this.toJSON())
  .map(([header, value]) => header + ': ' + value)
  .join('\n');

CanceledError(继承自 AxiosError

CanceledError 是请求被取消时抛出的错误类,继承自 AxiosError

constructor(message?: string, config?: InternalAxiosRequestConfig<D, P>, request?: any);
__CANCEL__?: boolean;

lib/cancel/CanceledError.js 的实现看,其默认消息为 'canceled',错误码固定为 AxiosError.ERR_CANCELED,并在实例上置 __CANCEL__ = true 标记——这正是 isCancel 的判定依据。

CancelCanceledError 的别名)

CancelCanceledError 的别名,仅为向前兼容而导出,将在未来版本移除:

Cancel: typeof CanceledError;

lib/axios.js 中可以看到挂载方式:axios.Cancel = axios.CanceledError;

isCancel

判断一个错误是否为 CanceledError 的函数。它适合用来区分「主动取消」与「意外错误」:

isCancel<T = any, D = any, P = any>(value: any): value is CanceledError<T, D, P>;

实现极简(lib/cancel/isCancel.js):

export default function isCancel(value) {
  return !!(value && value.__CANCEL__);
}

使用 AbortController 取消请求后的典型写法:

import axios from 'axios';

const controller = new AbortController();

axios.get('/api/data', { signal: controller.signal }).catch((error) => {
  if (axios.isCancel(error)) {
    console.log('Request was cancelled:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
});

controller.abort('User navigated away');

isAxiosError

判断一个错误是否为 AxiosError。建议在各 catch 块中使用它来安全地访问 error.responseerror.config 等 axios 专有属性:

isAxiosError(value: any): value is AxiosError;
import axios from 'axios';

try {
  await axios.get('/api/resource');
} catch (error) {
  if (axios.isAxiosError(error)) {
    // error.response, error.config, error.code are all available
    console.error('HTTP error', error.response?.status, error.message);
  } else {
    // A non-axios error (e.g. a programming mistake)
    throw error;
  }
}

该函数基于错误对象上的 isAxiosError 标记实现,位于 lib/helpers/isAxiosError.js

all(已废弃,改用 Promise.all

all 接收一个 Promise 数组,返回一个在所有 Promise 都完成时才 resolve 的单一 Promise。自 0.22.0 起已废弃,官方推荐使用 Promise.all。从源码看它现在也只是一个薄封装(lib/axios.js):

axios.all = function all(promises) {
  return Promise.all(promises);
};

spread

把数组参数展开后传入回调函数,适合在 Promise 链中把 [a, b] 形式参数拆开传给多参函数:

spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;

实现位于 lib/helpers/spread.js,常与 Promise 的数组结果搭配使用。

toFormData

把扁平或嵌套的 JavaScript 对象转换为 FormData 实例,适合以编程方式构建 multipart 表单数据:

toFormData(sourceObj: object, formData?: FormData, options?: FormSerializerOptions): FormData;
import { toFormData } from 'axios';

const data = { name: 'Jay', avatar: fileBlob };
const form = toFormData(data);
// form is now a FormData instance ready to post
await axios.post('/api/users', form);

实现位于 lib/helpers/toFormData.js;相关格式细节可参考 multipart-form-data-format.md

formToJSON

FormData 实例转换回扁平的 JavaScript 对象,便于以结构化形式读取表单数据。

只有点号与方括号记法是结构性的:.[] 用于分割路径,而 -、空格、+*& 等字符保留在字面键中。foo.barfoo[bar] 会创建嵌套对象,foo[] 会创建数组。

formToJSON(form: FormData): object;
import { formToJSON } from 'axios';

const form = new FormData();
form.append('user-name', 'johndoe');
form.append('user.name', 'john');

const obj = formToJSON(form);
console.log(obj);
// { 'user-name': 'johndoe', user: { name: 'john' } }

核心解析逻辑在 lib/helpers/formDataToJSON.js。另外注意 lib/axios.js 中挂载的版本对 HTMLFormElement 做了兼容:若传入 DOM 表单元素,会先构造 new FormData(thing) 再转换。

getAdapter

按名称解析并返回一个适配器函数,也可以传入候选名称数组按优先级逐一尝试。axios 内部正是用它为当前环境挑选最合适的适配器:

getAdapter(adapters: string | string[]): AxiosAdapter;
import { getAdapter } from 'axios';

// 显式获取 fetch 适配器
const fetchAdapter = getAdapter('fetch');

// 按优先级列表获取当前环境中最合适的适配器
const adapter = getAdapter(['fetch', 'xhr', 'http']);

lib/adapters/adapters.js 中的实现说明了候选机制的细节:内置的已知适配器为 http(Node.js)、xhr(浏览器 XMLHttpRequest)与 fetch(基于 fetch API)。对每个候选名依次检查是否可用,找到第一个可用的即返回;若全部不可用,则抛出带 ERR_NOT_SUPPORT 错误码的 AxiosError,错误消息会列出每个候选的拒绝原因(「环境不支持」或「构建中不可用」)。这也解释了为什么可以通过 getAdapter 在运行时诊断适配器问题。

mergeConfig

合并两个 axios 配置对象,采用的是与 axios 内部合并「默认值 + 单次请求选项」时完全相同的深度合并策略,后者的值具有更高优先级:

mergeConfig<D = any, P = any>(
  config1: AxiosRequestConfig<D, P>,
  config2: AxiosRequestConfig<D, P>
): AxiosRequestConfig<D, P>;
import { mergeConfig } from 'axios';

const base = { baseURL: 'https://api.example.com', timeout: 5000 };
const override = { timeout: 10000, headers: { 'X-Custom': 'value' } };

const merged = mergeConfig(base, override);
// { baseURL: 'https://api.example.com', timeout: 10000, headers: { 'X-Custom': 'value' } }

lib/core/mergeConfig.js 的实现可以看到几个关键设计:

  • 结果对象使用 null 原型对象Object.create(null))创建,避免下游读取 config.baseURL 等属性时继承到被污染的 Object.prototype 值;
  • 不同属性采用不同的合并策略:标量属性(如 urlmethodtimeout)由后者覆盖(valueFromConfig2),部分属性(如 baseURLurl 等实例级默认值)采用「默认取 config1、但 config2 显式给出时取 config2」的策略(defaultToConfig2),其余普通对象属性做深度合并(mergeDeepProperties);
  • 头对象(AxiosHeaders 实例)在参与合并时会先展开为普通对象,因此合并后得到的是可再序列化的普通对象而非 AxiosHeaders 实例。

常量

HttpStatusCode

一个把 HTTP 状态码收录为具名常量的对象,用于书写比裸数字更可读的条件判断:

import axios, { HttpStatusCode } from 'axios';

try {
  const response = await axios.get('/api/resource');
} catch (error) {
  if (axios.isAxiosError(error)) {
    if (error.response?.status === HttpStatusCode.NotFound) {
      console.error('Resource not found');
    } else if (error.response?.status === HttpStatusCode.Unauthorized) {
      console.error('Authentication required');
    }
  }
}

lib/helpers/HttpStatusCode.js 中按 1xx–5xx 分段定义了完整的具名常量,例如 Ok: 200NoContent: 204MovedPermanently: 301NotFound: 404TooManyRequests: 429InternalServerError: 500 等。另外注意其中两个命名更新:PayloadTooLarge(413)与 UnprocessableEntity(422)已被标记为 deprecated,源码注释建议改用新命名 ContentTooLargeUnprocessableContent(两者当前取值相同)。

其他

VERSION

axios 包当前的版本号,是一个字符串,随每次发布更新。源码中它来自构建时生成的 lib/env/data.js(该文件由 gulpfile.js 构建流程写入),再经由 axios.VERSION 导出,可用于在运行时打印或上报当前加载的 axios 版本。

登录后查看全文
热门项目推荐
相关项目推荐