# @contentful/axios 中文文档

规范地址：https://npmcn.com/package/%40contentful/axios/

版本：0\.18\.0
npm 元数据更新时间：2026-05-28T10:24:51.341Z
中文译文更新时间：2026-11-10T16:40:58.150Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40contentful/axios
原文对照：https://npmcn.com/package/%40contentful/axios/?lang=original
项目主页：https://github.com/axios/axios
源码仓库：https://github.com/contentful/axios

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

- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2017-11-16T14:09:50.847Z
- 最新版本发布：2017-11-16T14:09:50.847Z
- 近 30 天下载量：20899（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

为浏览器和节点提供基于 HTTP 客户端的承诺

## 安装

```sh
npm install @contentful/axios
```

也可以使用：`pnpm add @contentful/axios`、`yarn add @contentful/axios`、`bun add @contentful/axios`

## README

# 轴

[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)

为浏览器和节点提供基于 HTTP 客户端的承诺

## 特征

-   制作 [XMLHttp 请求](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) 从浏览器中
-   制作 [网页](http://nodejs.org/api/http.html) 来自节点.js的请求
-   支持 [答应](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API 密码
-   拦截请求和答复
-   变换请求和响应数据
-   取消请求
-   JSON 数据的自动转换
-   客户端保护支持 [预算外](http://en.wikipedia.org/wiki/Cross-site_request_forgery)

## 浏览器支持

| ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) |
| --- | --- | --- | --- | --- | --- |
| 最近的报告 | 最近的报告 | 最近的报告 | 最近的报告 | 最近的报告 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |

[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)

## 安装

使用 npm :

```bash
$ npm install axios
```

使用弓箭手 :

```bash
$ bower install axios
```

使用 cdn :

```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```

## 示例

执行a `GET` 请求

```js
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
```

执行a `POST` 请求

```js
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
```

执行多项并行请求

```js
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
```

## 轴 API

可通过将相关配置传递给 `axios`。 。 。 .

##### axios( 配置)

```js
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
```

```js
// GET request for remote image
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
```

##### axios( url \[, 配置\] )

```js
// Send a GET request (default method)
axios('/user/12345');
```

### 请求方法别名

为方便起见,为所有支持的请求方法提供了别名.

##### axios. request( 配置)

##### arxios.get(url\[,配置\])

##### arxios.delete(url \[, config\]) (韩语)

##### axios.head(url \[, config\]) (中文(简体) )

##### axios. options( url\[, config\] ) (韩语)

##### axios.post(url\[,数据\[,配置\]\])

##### axios.put(url\[,数据\[,配置\]\])

##### axios.patch(url\[,数据\[,配置\]\])

###### 页:1

使用别名方法时 `url`, (中文(简体) ), `method`,以及 `data` 属性不需要在配置中指定.

### 货币

处理同时提出的请求的助手职能.

##### axios.all(可渗出)

##### axios.spread(回调)

### 创建实例

您可以用自定义配置创建新 arxios 实例 .

##### axios.create(\[配置\])

```js
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
```

### 实例方法

现有实例方法如下。 指定的配置将会与实例配置合并 .

##### axios# 请求( 配置)

##### axios# get( url \[, 配置\] )

##### axios#delete(url\[, config\]) (韩语)

##### axios# head( url \[, 配置\])

##### axios# 选项( url\[, 配置\])

##### axios# post( url\[, 数据\[, 配置\] \])

##### axios# put( url\[, 数据 \[, 配置\] \]) )

##### axios# patch( url \[, 数据 \[, 配置\] \]) )

## 请求配置

这些是可用于提出请求的配置选项。 只有 `url` 需要时间。 请求将默认为 `GET` 若为 `method` 未指定.

```js
{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000,

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}
```

## 反应Schema

对请求的答复载有下列资料.

```js
{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}
```

使用时 `then`,您将收到如下答复:

```js
axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
```

使用时 `catch`,或通过 [拒绝回调](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) 作为第二个参数 `then`,答复将通过 `error` 所解释的对象 [处理出错](https://npmcn.com/package/%40contentful/axios/#readme-handling-errors) 节.

## 配置默认值

您可以指定适用于每个请求的配置默认值.

### 全球轴默认值

```js
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```

### 自定义实例默认值

```js
// Set config defaults when creating the instance
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
```

### 位次顺序

将合并为优先级。 命令是库默认值 `lib/defaults.js`,则 `defaults` 财产,最后 `config` 请求的理由。 后者将优先于前者。 举个例子.

```js
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
var instance = axios.create();

// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});
```

## 截取器

在请求或答复被处理之前,您可以截获请求或答复 `then` 或者说 `catch`。 。 。 .

```js
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });
```

如果你以后需要移除一个拦截器的话.

```js
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
```

您可以在自定义的轴上添加截取器 .

```js
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
```

## 处理出错

```js
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
```

您可以使用 : `validateStatus` 配置选项 .

```js
axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})
```

## 取消

您可以使用 _取消签名_。 。 。 .

> 轴取消符号 API 是基于撤回的 [可取消的承诺提案](https://github.com/tc39/proposal-cancelable-promises)。 。 。 .

您可以使用 `CancelToken.source` 如下所示:

```js
var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
```

您也可以通过将执行器函数传递到 `CancelToken` 构造器 :

```js
var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();
```

> 注意: 您可以用相同的取消令牌取消多个请求 .

## 使用应用程序/x-www-form-urlencoded格式

默认情况下, Axios 序列化 JavaScript 对象为 `JSON`中发送数据 `application/x-www-form-urlencoded` 格式,您可以使用以下选项之一.

### 浏览器

在浏览器中,您可以使用 [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API如下:

```js
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
```

> 请注意: `URLSearchParams` 不为所有浏览器所支持(参见 [caniuse.com (英语)](http://www.caniuse.com/#feat=urlsearchparams)),但有一个 [多边填充](https://github.com/WebReflection/url-search-params) 可用(确保全球环境的多填充).

或者,您可以使用 [`qs`](https://github.com/ljharb/qs) 库 :

```js
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
```

### 节点.js

在节点.js,你可以使用 [`querystring`](https://nodejs.org/api/querystring.html) 模块如下:

```js
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
```

你也可以使用这个 [`qs`](https://github.com/ljharb/qs) 图书馆.

## 塞姆维尔

直到轴线达到 `1.0` 发布时,会以一个新的小版本发布断开的更改. 举个例子 `0.5.1`,以及 `0.5.4` 将拥有相同的API,但 `0.6.0` 会有突破性变化.

## 承诺

axios 取决于本地ES6 承诺的执行 [支持](http://caniuse.com/promises)。 。 。 . 如果你的环境不支持ES6承诺,你可以 [多边填充](https://github.com/jakearchibald/es6-promise)。 。 。 .

## 类型脚本

axios 包括 [类型脚本](http://typescriptlang.org/) 定义.

```typescript
import axios from 'axios';
axios.get('/user?ID=12345');
```

## 资源

-   [更改日志](https://github.com/axios/axios/blob/master/CHANGELOG.md)
-   [升级指南](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
-   [生态系统](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
-   [贡献指南](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
-   [行为守则](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)

## 贷项

axios的灵感很大 [http服务](https://docs.angularjs.org/api/ng/service/$http) 提供情况 [角质](https://angularjs.org/). 归根结底是努力提供独立的 `$http`\- 像是Angular以外的服务.

## 许可证

麻省理工学院

## 常见问题

### @contentful/axios 是什么？

为浏览器和节点提供基于 HTTP 客户端的承诺

### 如何安装 @contentful/axios？

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

### @contentful/axios 支持 TypeScript 吗？

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

### @contentful/axios 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @contentful/axios 可以商用吗？

@contentful/axios 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @contentful/axios 的下载量有多少？

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

### @contentful/axios 还在维护吗？

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

