# gaxios 中文文档

规范地址：https://npmcn.com/package/gaxios/

版本：8\.3\.2
npm 元数据更新时间：2026-10-23T17:59:49.111Z
中文译文更新时间：2026-11-05T14:50:28.625Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/gaxios
原文对照：https://npmcn.com/package/gaxios/?lang=original
项目主页：https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios
源码仓库：https://github.com/googleapis/google-cloud-node

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：231 kB，40 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：3 个
- 首次发布：2018-11-10T23:19:19.832Z
- 最新版本发布：2026-10-23T17:59:48.868Z
- 近 30 天下载量：511115014（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：105（近 12 个月 12 个）

## 中文简介

一个专门为Google API和服务的简单的普通HTTP客户端.

## 安装

```sh
npm install gaxios
```

也可以使用：`pnpm add gaxios`、`yarn add gaxios`、`bun add gaxios`

## README

# 加克西奥斯

[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios) [![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios) [![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts)

> HTTP 请求客户端提供 `axios` 如界面在顶端 `node-fetch`。 。 。 .

## 安装

```sh
$ npm install gaxios
```

## 示例

```js
import {request} from 'gaxios';
const res = await request({url: 'https://google.com/'});
```

## `fetch`\- 可兼容的 API 示例

我们提供一个客栈 `fetch`\- 兼容的API也一样.

```js
import {instance} from 'gaxios';
const res = await instance.fetch('https://google.com/');
```

无法在 `res.data`设置 `{responseType: 'stream'}` 或者说 `.adapter` gaxios 实例的默认或请求.

## 设置默认

Gaxios 支持在默认实例和附加实例上设置默认属性 。 这在向具有相同基础设置的同域提出许多请求时往往有用. 例如:

```js
import {Gaxios} from 'gaxios';

const gaxios = new Gaxios();

gaxios.defaults = {
  baseURL: 'https://example.com'
  headers: new Headers({
    Authorization: 'SOME_TOKEN'
  })
}

await gaxios.request({url: '/data'});
```

注意设置默认值优先 相对于其他认证方法,即应用程序默认证书.

## `GaxiosResponse`

这个 `GaxiosResponse` 对象延伸 `fetch` API的软件 [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) 对象,并添加:

-   `config`:请求所用的配置.
-   `data`: 转变 `.body`,例如JSON,文本,阵列缓冲器,或更多.

## 请求选项

```ts
interface GaxiosOptions = {
  // The url to which the request should be sent.  Required.
  url: string | URL,

  // The HTTP method to use for the request.  Defaults to `GET`.
  method: 'GET',

  // The base Url to use for the request.
  // Resolved as `new URL(url, baseURL)`
  baseURL: 'https://example.com/v1/' | URL;

  // The HTTP methods to be sent with the request.
  headers: new Headers(),

  // The data to send in the body of the request. Objects will be serialized as JSON
  // except for:
  // - `ArrayBuffer`
  // - `Blob`
  // - `Buffer` (Node.js)
  // - `DataView`
  // - `File`
  // - `FormData`
  // - `ReadableStream`
  // - `stream.Readable` (Node.js)
  // - strings
  // - `TypedArray` (e.g. `Uint8Array`, `BigInt64Array`)
  // - `URLSearchParams`
  // - all other objects where:
  //   - headers.get('Content-Type') === 'application/x-www-form-urlencoded' (as they will be serialized as `URLSearchParams`)
  //
  // Here are a few examples that would prevent setting `Content-Type: application/json` by default:
  // - data: JSON.stringify({some: 'data'}) // a `string`
  // - data: fs.readFile('./some-data.jpeg') // a `stream.Readable`
  data: {
    some: 'data'
  },

  // The max size of the http response content in bytes allowed.
  // Defaults to `0`, which is the same as unset.
  maxContentLength: 2000,

  // The query parameters that will be encoded using `URLSearchParams` and
  // appended to the url
  params: {
    querystring: 'parameters'
  },

  // The timeout for the HTTP request in milliseconds. No timeout by default.
  timeout: 60000,

  // Optional method to override making the actual HTTP request. Useful
  // for writing tests and instrumentation
  adapter?: async (options, defaultAdapter) => {
    const res = await defaultAdapter(options);
    res.data = {
      ...res.data,
      extraProperty: 'your extra property',
    };
    return res;
  };

  // The expected return type of the request.  Options are:
  // 'json' | 'stream' | 'blob' | 'arraybuffer' | 'text' | 'unknown'
  // Defaults to `unknown`.
  //
  // If the `fetchImplementation` is native `fetch`, the
  // stream is a `ReadableStream`, otherwise `readable.Stream`.
  //
  // Note: Setting 'stream' does not consume the `Response#body` - this can
  // be useful for passthrough requests, where a consumer would like to
  // transform the `Response#body`, or for using Gaxios as a drop-in `fetch`
  // replacement.
  responseType: 'unknown',

  // The node.js http agent to use for the request.
  agent: someHttpsAgent,

  // Custom function to determine if the response is valid based on the
  // status code.  Defaults to (>= 200 && < 300)
  validateStatus: (status: number) => true,

  /**
   * Implementation of `fetch` to use when making the API call. Will use
   * `fetch` by default.
   */
  fetchImplementation?: (
    ...args: Parameters<typeof fetch>
  ) => ReturnType<typeof fetch>;

  // Configuration for retrying of requests.
  retryConfig: {
    // The number of times to retry the request.  Defaults to 3.
    retry?: number;

    // The number of retries already attempted.
    currentRetryAttempt?: number;

    // The HTTP Methods that will be automatically retried.
    // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
    httpMethodsToRetry?: string[];

    // The HTTP response status codes that will automatically be retried.
    // Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]
    statusCodesToRetry?: number[][];

    // Function to invoke when a retry attempt is made.
    onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;

    // Function to invoke which determines if you should retry
    shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;

    // When there is no response, the number of retries to attempt. Defaults to 2.
    noResponseRetries?: number;

    // The amount of time to initially delay the retry, in ms.  Defaults to 100ms.
    retryDelay?: number;
  },

  // Enables default configuration for retries.
  retry: boolean,

  // Enables aborting via AbortController
  signal?: AbortSignal

  /**
   * A collection of parts to send as a `Content-Type: multipart/related` request.
   */
  multipart?: GaxiosMultipartOptions;

  /**
   * An optional proxy to use for requests.
   * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available.
   * The `agent` option overrides this.
   *
   * @see {@link GaxiosOptions.noProxy}
   * @see {@link GaxiosOptions.agent}
   */
  proxy?: string | URL;

  /**
   * A list for excluding traffic for proxies.
   * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules.
   *
   * - When provided a string, it is matched by
   *   - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`)
   * - When provided a URL, it is matched by the `.origin` property.
   *   - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use:
   *     - new URL('https://example.com')
   *     - new URL('https://example.com:443')
   *   - The following would be used with a proxy:
   *     - new URL('http://example.com:80')
   *     - new URL('https://example.com:8443')
   * - When provided a regular expression it is used to match the stringified URL
   *
   * @see {@link GaxiosOptions.proxy}
   */
  noProxy?: (string | URL | RegExp)[];

  /**
   * An experimental, customizable error redactor.
   *
   * Set `false` to disable.
   *
   * @remarks
   *
   * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see:
   * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs
   * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets
   *
   * @experimental
   */
  errorRedactor?: typeof defaultErrorRedactor | false;
}
```

## 许可证

[阿帕奇 - 2.0](https://github.com/googleapis/gaxios/blob/main/LICENSE)

## 常见问题

### gaxios 是什么？

一个专门为Google API和服务的简单的普通HTTP客户端\.

### 如何安装 gaxios？

在项目目录运行 npm install gaxios，或使用 pnpm add / yarn add / bun add。

### gaxios 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### gaxios 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### gaxios 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### gaxios 可以商用吗？

gaxios 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### gaxios 的下载量有多少？

根据 npm 官方下载统计，gaxios 在 2026/10/07 – 2026/11/05 这 30 天内被下载 511,115,014 次，日均约 17,037,167 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### gaxios 还在维护吗？

最新版本 8\.3\.2 发布于 2026/10/24（15 天前）；至今共发布 105 个版本，其中过去 12 个月发布了 12 个；首次发布于 2018/11/11。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

