mirror of
https://github.com/tenrok/axios.git
synced 2026-06-17 19:21:29 +03:00
docs: publish v1.17.0 release notes (#10988)
This commit is contained in:
@@ -51,3 +51,8 @@ The rules below are a Copilot-facing subset of the load-bearing safety guarantee
|
||||
- Do not mutate config objects in place; return new ones from merges/transforms.
|
||||
- Do not assume browser- or Node-only globals exist; capability-check first.
|
||||
- Validate options through the existing `validator` helper rather than inventing ad-hoc validation paths.
|
||||
|
||||
## Pre-release tracking
|
||||
|
||||
- Add user-visible unreleased changes to `PRE_RELEASE_CHANGELOG.md`, not `CHANGELOG.md`.
|
||||
- Track deferred README, docs site, examples, migration guide, and translated docs updates in `PRE_RELEASE_DOCS.md`; do not update release docs for unreleased runtime/API changes unless explicitly doing release preparation.
|
||||
|
||||
@@ -36,7 +36,8 @@ This file is the canonical contributor guide for both human and AI agents workin
|
||||
## Pre-Release Notes
|
||||
|
||||
- Add user-visible unreleased changes to `PRE_RELEASE_CHANGELOG.md`, not `CHANGELOG.md`. `CHANGELOG.md` is release-owned and should only be updated as part of preparing an actual release.
|
||||
- Do not update `README.md` or the docs site for unreleased runtime/API changes unless the task is explicitly release preparation. Instead, record the exact README/docs updates needed under `PRE_RELEASE_CHANGELOG.md` so they can be applied during release work.
|
||||
- Track deferred README, docs site, examples, migration guide, and translated docs updates in `PRE_RELEASE_DOCS.md`. Use enough context for release preparation; do not store brittle diffs or line-number-only notes.
|
||||
- Do not update `README.md` or the docs site for unreleased runtime/API changes unless the task is explicitly release preparation. During feature/fix work, record what docs need to say in `PRE_RELEASE_DOCS.md` so it can be applied during release work.
|
||||
|
||||
## Architecture Boundaries
|
||||
|
||||
|
||||
@@ -1,5 +1,56 @@
|
||||
# Changelog
|
||||
|
||||
## v1.17.0 — June 1, 2026
|
||||
|
||||
This release adds Node HTTP zstd decompression, hardens config and release workflows, and fixes authentication, header, proxy, and type-handling regressions.
|
||||
|
||||
## 🔒 Security Fixes
|
||||
|
||||
* **Config Hardening:** Guarded `socketPath`, `params`, and `paramsSerializer` reads with own-property checks to prevent inherited prototype values from affecting request behavior, including SSRF-sensitive paths. (__#10901__, __#10922__)
|
||||
* **Release Publishing:** Switched the publish workflow to npm staged publishing for safer, auditable package releases with provenance. (__#10926__)
|
||||
|
||||
## 🚀 New Features
|
||||
|
||||
* **HTTP Compression:** Added Node HTTP adapter support for zstd response decompression, with `transitional.advertiseZstdAcceptEncoding` controlling whether `zstd` is advertised in `Accept-Encoding`. (__#6792__, __#10920__)
|
||||
|
||||
## 🐛 Bug Fixes
|
||||
|
||||
* **Authentication Handling:** Restored Basic auth on same-origin Node redirects while continuing to strip credentials cross-origin, and aligned the fetch adapter with HTTP adapter behavior for URL-embedded Basic auth. (__#10929__, __#10896__)
|
||||
* **Proxy TLS:** Preserved user `httpsAgent` TLS options when tunneling HTTPS requests through HTTP CONNECT proxies. (__#10957__)
|
||||
* **React Native FormData:** Cleared default `Content-Type` for React Native `FormData` so multipart boundaries can be generated correctly. (__#10898__)
|
||||
* **Headers:** Silently skipped empty or whitespace-only header names instead of throwing, matching parsed-header behavior and avoiding React Native response crashes. (__#10875__)
|
||||
* **Request Data Merging:** Preserved enumerable symbol keys when cloning plain request data through axios merge logic. (__#10812__)
|
||||
* **Bundler Compatibility:** Converted `resolveConfig` from an arrow default export to a named function export to avoid webpack and Babel transform interop failures. (__#10891__)
|
||||
* **Types:** Corrected `AxiosHeaders.toJSON()` return types and updated CommonJS `isCancel` typings to narrow to `CanceledError<T>`. (__#10956__, __#10952__)
|
||||
* **Build Tooling:** Avoided emitting a null `Authorization` header from the GitHub build helper when `GITHUB_TOKEN` is unset. (__#10931__)
|
||||
|
||||
## 🔧 Maintenance & Chores
|
||||
|
||||
* **HTTP/2 Internals:** Extracted `Http2Sessions` into its own helper module and added direct unit coverage for session pooling, timeout, and cleanup behavior. (__#10861__)
|
||||
* **Package Publishing:** Reduced published package size by switching to a `files` allowlist and dropping unneeded unminified bundle source maps. (__#10939__)
|
||||
* **CI and Release Automation:** Added bundle-size reporting, moved reports to the job summary, fixed bundle-size comparison coverage, added Node 26 to the matrix, pinned npm for staged publishing, and prepared the 1.17.0 release. (__#10907__, __#10911__, __#10916__, __#10927__, __#10935__, __#10983__)
|
||||
* **Developer Workflow:** Added a dev container and iterated on OpenSpec workflow files before removing them from the release branch. (__#10925__, __#10914__, __#10958__)
|
||||
* **Documentation and Policy:** Updated disclosure, contributor, collaboration, threat-model, advanced docs, README badges, release notes, moderator configuration, and project metadata. (__#10890__, __#10889__, __#10921__, __#10945__, __#10905__, __#10933__, __#10915__, __#10887__, __#10955__)
|
||||
* **Dependencies:** Bumped Babel tooling, Commitlint, ESLint, Rollup, Globals, Vitest, Playwright, `fs-extra`, `qs`, docs dependencies, and GitHub Actions dependencies including `actions/dependency-review-action` and `zizmorcore/zizmor-action`. (__#10871__, __#10879__, __#10918__, __#10919__, __#10934__, __#10947__, __#10954__, __#10960__)
|
||||
|
||||
## 🌟 New Contributors
|
||||
|
||||
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
|
||||
|
||||
* __@BasixKOR__ (__#6792__)
|
||||
* __@carladams1299-lab__ (__#10861__)
|
||||
* __@LaplaceYoung__ (__#10812__)
|
||||
* __@JamieMagee__ (__#10939__)
|
||||
* __@RonGamzu__ (__#10905__)
|
||||
* __@sapirbaruch__ (__#10891__)
|
||||
* __@nezukoagent__ (__#10901__)
|
||||
* __@devareddy05__ (__#10929__)
|
||||
* __@Mohammad-Faiz-Cloud-Engineer__ (__#10922__)
|
||||
* __@azandabot__ (__#10931__)
|
||||
* __@niksy__ (__#10896__)
|
||||
|
||||
[Full Changelog](https://github.com/axios/axios/compare/v1.16.1...v1.17.0)
|
||||
|
||||
## v1.16.1 — May 13, 2026
|
||||
|
||||
This release ships a defence-in-depth fix for prototype pollution in `formDataToJSON`, hardens proxy and CI workflows, restores Webpack 4 compatibility for the fetch adapter, and includes several small bug fixes and maintenance improvements.
|
||||
|
||||
@@ -6,35 +6,6 @@
|
||||
|
||||
- **HTTP Adapter Redirects:** Added a Node.js `sensitiveHeaders` request config option that strips caller-selected custom secret headers from cross-origin redirects. (**#10892**)
|
||||
|
||||
## Docs updates
|
||||
|
||||
- docs/pages/misc/security.md LN29 : | [`sensitiveHeaders`](/pages/advanced/request-config#sensitiveheaders) | Custom authentication headers such as `X-API-Key` can be forwarded to a different origin when a trusted server redirects there. | List custom secret-bearing headers in `sensitiveHeaders` so the Node.js adapter strips them on cross-origin redirects. |
|
||||
- docs/pages/advanced/request-config.md LN269 : | ### `sensitiveHeaders` <Badge type="warning" text="Node.js only" />
|
||||
|
||||
The `sensitiveHeaders` property is an optional array of custom secret-bearing header names to remove when axios follows a redirect to a different origin. Matching is case-insensitive. Same-origin redirects keep these headers.
|
||||
|
||||
This only applies to redirects followed by the Node.js HTTP adapter. If `maxRedirects` is set to 0, `sensitiveHeaders` is not used.
|
||||
|
||||
```js
|
||||
axios.get('https://api.example.com/users', {
|
||||
headers: { 'X-API-Key': 'secret' },
|
||||
sensitiveHeaders: ['X-API-Key']
|
||||
});
|
||||
```
|
||||
|
||||
## New Features
|
||||
|
||||
- **HTTP Adapter - Zstandard:** Added automatic zstd decompression on Node.js versions that support it. `zstd` is only advertised in the default `Accept-Encoding` header when `transitional.advertiseZstdAcceptEncoding: true` is set. (**#6792**)
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
- **AxiosHeaders:** Silently skip empty response header names emitted by some React Native Android responses instead of throwing. (**#6959**, **#10875**)
|
||||
- **Config Security:** Ignore inherited `params` and `paramsSerializer` values when resolving request config, preventing prototype-pollution gadgets from changing serialized URLs. (**#10922**)
|
||||
- **Fetch Adapter - Auth:** Support HTTP Basic credentials embedded in request URLs, including UTF-8 credentials, while stripping credentials before constructing the fetch `Request` and preserving `config.auth` precedence. (**#10896**)
|
||||
- **Types:** Add the missing readonly `name: 'CanceledError'` declaration to CommonJS `CanceledError` typings to match the ESM declarations. (**#10922**)
|
||||
- **Types:** Correct the CommonJS `isCancel` type guard to narrow cancellation errors to `CanceledError<T>`, matching the ESM declaration. (**#10952**)
|
||||
- **HTTP Adapter - Auth on Redirect:** HTTP Basic credentials supplied via `config.auth` are now restored on same-origin redirects, fixing a regression caused by `follow-redirects` >= 1.15.8 that broke `POST` requests answered with a 303 Location. Cross-origin redirects continue to drop credentials, preserving the existing T-R2 mitigation in `THREATMODEL.md`. (**#6929**)
|
||||
- **HTTP Adapter - Proxy TLS:** Preserve `httpsAgent` TLS options such as `ca` and `rejectUnauthorized` for HTTPS origins reached through a CONNECT proxy tunnel. (**#10953**)
|
||||
- **HTTP Adapter - Socket Path:** Ignore inherited `socketPath` and `allowedSocketPaths` config values when building Node.js requests, preventing prototype-pollution SSRF via Unix sockets. (**#10901**)
|
||||
- **React Native FormData:** Clear the default `Content-Type` header for React Native `FormData` requests so Android can build multipart bodies with the correct boundary. (**#10898**)
|
||||
- **Request Data:** Preserve enumerable symbol keys when merging plain request data before `transformRequest`. (**#6392**)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# Pre-Release Documentation Notes
|
||||
|
||||
## Purpose
|
||||
|
||||
Track documentation updates that should be applied during release preparation.
|
||||
|
||||
Do not treat this file as final documentation. Each entry should give enough context for a maintainer or LLM to update README, docs pages, examples, migration guides, and translated docs when the release is prepared.
|
||||
|
||||
Do not store raw diffs or line-number-only instructions here; prefer stable section names, target files, required concepts, examples, and release-specific notes.
|
||||
|
||||
## Entry Format
|
||||
|
||||
- **Change:** Short feature/fix name.
|
||||
- **Source:** PR, issue, or changelog reference.
|
||||
- **Status:** Pending | Applied | Skipped.
|
||||
- **Docs targets:** Files or docs sections likely needing updates.
|
||||
- **Required content:** What the docs must explain.
|
||||
- **Examples:** Any code snippets or examples that should be included.
|
||||
- **Notes:** Constraints, release-only wording, translation follow-up, etc.
|
||||
|
||||
## Unreleased
|
||||
|
||||
### sensitiveHeaders request config
|
||||
|
||||
- **Change:** Document the Node.js `sensitiveHeaders` request config option for stripping custom secret headers from cross-origin redirects.
|
||||
- **Source:** `PRE_RELEASE_CHANGELOG.md` Security Fixes, #10892.
|
||||
- **Status:** Pending.
|
||||
- **Docs targets:** `docs/pages/misc/security.md`; `docs/pages/advanced/request-config.md`; README request config section if it lists all config options; translated docs after English docs are finalized.
|
||||
- **Required content:** Explain that `sensitiveHeaders` is an optional array of custom secret-bearing header names. Matching is case-insensitive. The Node.js HTTP adapter removes matching headers only when following a redirect to a different origin. Same-origin redirects keep these headers. If `maxRedirects` is `0`, axios does not follow redirects and `sensitiveHeaders` is not used. Mention common custom authentication headers such as `X-API-Key`.
|
||||
- **Examples:** Include this request example.
|
||||
|
||||
```js
|
||||
axios.get('https://api.example.com/users', {
|
||||
headers: { 'X-API-Key': 'secret' },
|
||||
sensitiveHeaders: ['X-API-Key']
|
||||
});
|
||||
```
|
||||
|
||||
- **Notes:** Add a security page row linking to the request-config section and add a `sensitiveHeaders` request-config entry marked Node.js only.
|
||||
@@ -773,6 +773,7 @@ These config options are available for requests. Only `url` is required. Request
|
||||
// When no `transformRequest` is set, it must be of one of the following types:
|
||||
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
|
||||
// - Browser only: FormData, File, Blob
|
||||
// - React Native: FormData
|
||||
// - Node only: Stream, Buffer, FormData (form-data package)
|
||||
data: {
|
||||
firstName: 'Fred'
|
||||
@@ -877,10 +878,12 @@ These config options are available for requests. Only `url` is required. Request
|
||||
// Do whatever you want with the Axios progress event
|
||||
},
|
||||
|
||||
// `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
|
||||
// `maxContentLength` defines the max size of the response content in bytes.
|
||||
// It is enforced by the Node.js HTTP adapter and the fetch adapter.
|
||||
maxContentLength: 2000,
|
||||
|
||||
// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
|
||||
// `maxBodyLength` defines the max size of the request content in bytes.
|
||||
// It is enforced by the Node.js HTTP adapter and the fetch adapter when the body length can be determined.
|
||||
maxBodyLength: 2000,
|
||||
|
||||
// `redact` masks matching config keys when AxiosError#toJSON() is called.
|
||||
@@ -1646,6 +1649,7 @@ server = app.listen(3000);
|
||||
|
||||
To send data as `multipart/form-data`, pass a FormData instance as the payload.
|
||||
You do not need to set the `Content-Type` header. Axios detects it from the payload type.
|
||||
For browser, web worker, and React Native `FormData`, leave `Content-Type` unset so the runtime can add the multipart boundary.
|
||||
|
||||
```js
|
||||
const formData = new FormData();
|
||||
@@ -2074,6 +2078,8 @@ The `rewrite` argument controls the overwriting behavior:
|
||||
|
||||
The option can also accept a user-defined function that determines whether to overwrite the value.
|
||||
|
||||
Empty or whitespace-only header names are ignored.
|
||||
|
||||
Returns `this`.
|
||||
|
||||
### AxiosHeaders#get(header)
|
||||
@@ -2249,6 +2255,8 @@ const { data } = fetchAxios.get(url);
|
||||
The adapter supports the same features as the `xhr` adapter, including upload and download progress capturing.
|
||||
It also supports response types such as `stream` and `formdata` when the environment supports them.
|
||||
|
||||
When `auth` is omitted, the fetch adapter can read HTTP Basic auth credentials from the request URL, for example `https://user:pass@example.com`. Percent-encoded URL credentials are decoded before the `Authorization` header is generated, and `auth` takes precedence over URL-embedded credentials.
|
||||
|
||||
### Custom fetch
|
||||
|
||||
Since `v1.12.0`, you can configure the fetch adapter to use a custom fetch API instead of environment globals.
|
||||
@@ -2371,6 +2379,20 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
Use `axios.isCancel<T>()` to narrow cancellation errors to `CanceledError<T>`:
|
||||
|
||||
```typescript
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
await axios.get<User>('/user?ID=12345', { signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (axios.isCancel<User>(error)) {
|
||||
handleCancellation(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Because axios publishes an ESM default export and a CJS `module.exports`, TypeScript has a few caveats.
|
||||
The recommended setting is `"moduleResolution": "node16"`, which is implied by `"module": "node16"`. This requires TypeScript 4.7 or greater.
|
||||
If you use ESM, your settings should be fine.
|
||||
|
||||
@@ -97,6 +97,7 @@ constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
|
||||
#### `set`
|
||||
|
||||
Agrega un encabezado al objeto de encabezados.
|
||||
Los nombres de encabezado vacíos o compuestos solo por espacios se ignoran.
|
||||
|
||||
```ts
|
||||
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
||||
|
||||
@@ -12,6 +12,8 @@ const instance = axios.create({
|
||||
|
||||
El adaptador admite la misma funcionalidad que el adaptador `xhr`, incluyendo la captura del progreso de carga y descarga. También admite tipos de respuesta adicionales como `stream` y `formdata` (si el entorno lo soporta).
|
||||
|
||||
Cuando `auth` se omite, el adaptador fetch puede leer credenciales de autenticación HTTP Basic desde la URL de la solicitud, por ejemplo `https://user:pass@example.com`. Las credenciales de URL codificadas con porcentaje se decodifican antes de generar el encabezado `Authorization`, y `auth` tiene prioridad sobre las credenciales incluidas en la URL.
|
||||
|
||||
## Fetch personalizado <Badge type="tip" text="v1.12.0+" />
|
||||
|
||||
A partir de `v1.12.0`, puedes personalizar el adaptador fetch para que use una función `fetch` personalizada en lugar de la global del entorno. Puedes pasar una función `fetch` personalizada, y los constructores `Request` y `Response` a través de la opción de configuración `env`. Esto es útil cuando trabajas con entornos personalizados o frameworks de aplicación que proporcionan su propia implementación de `fetch`.
|
||||
|
||||
@@ -45,6 +45,8 @@ El argumento `rewrite` controla el comportamiento de sobreescritura:
|
||||
|
||||
La opción también puede aceptar una función definida por el usuario que determina si el valor debe ser sobreescrito o no. La función recibe el valor actual, el nombre del encabezado y el objeto de encabezados como argumentos.
|
||||
|
||||
Los nombres de encabezado vacíos o compuestos solo por espacios se ignoran.
|
||||
|
||||
`AxiosHeaders` conserva el formato de la primera clave coincidente que encuentra. Puedes usar esto para preservar el formato específico de un encabezado inicializando una clave con `undefined` y luego estableciendo los valores posteriormente. Consulta [Preservar el formato de un encabezado específico](/pages/advanced/headers#preserving-a-specific-header-case).
|
||||
|
||||
## Get (Obtener)
|
||||
|
||||
@@ -9,6 +9,8 @@ formData.append('foo', 'bar');
|
||||
axios.post('https://httpbin.org/post', formData);
|
||||
```
|
||||
|
||||
No establezcas manualmente el encabezado `Content-Type` para `FormData` en navegador, web worker o React Native; esos entornos agregan el boundary multipart por sí mismos.
|
||||
|
||||
En Node.js, puedes usar la librería `form-data` de la siguiente manera:
|
||||
|
||||
```js
|
||||
|
||||
@@ -119,8 +119,11 @@ El `data` son los datos que se enviarán como cuerpo de la solicitud. Puede ser
|
||||
|
||||
- cadena de texto, objeto plano, ArrayBuffer, ArrayBufferView, URLSearchParams
|
||||
- Solo en el navegador: FormData, File, Blob
|
||||
- React Native: FormData
|
||||
- Solo en Node.js: Stream, Buffer, FormData (paquete form-data)
|
||||
|
||||
Para `FormData` en navegador, web worker y React Native, no establezcas manualmente `Content-Type`; el entorno agrega el boundary multipart.
|
||||
|
||||
Para los objetos `FormData` de Node.js que proporcionan un método `getHeaders()`, axios copia por defecto todos los encabezados devueltos para mantener la compatibilidad con v1. Si el objeto `FormData` es personalizado o no es de plena confianza, establece `formDataHeaderPolicy: 'content-only'` para copiar únicamente `Content-Type` y `Content-Length`, y define cualquier otro encabezado de la solicitud explícitamente mediante la configuración `headers`.
|
||||
|
||||
### `formDataHeaderPolicy` <Badge type="warning" text="Solo en Node.js" />
|
||||
@@ -231,16 +234,16 @@ La función `onUploadProgress` te permite escuchar el progreso de una carga.
|
||||
|
||||
La función `onDownloadProgress` te permite escuchar el progreso de una descarga.
|
||||
|
||||
### `maxContentLength` <Badge type="warning" text="Solo en Node.js" />
|
||||
### `maxContentLength` <Badge type="warning" text="HTTP Node.js/fetch" />
|
||||
|
||||
La propiedad `maxContentLength` define el número máximo de bytes que el servidor aceptará en la respuesta.
|
||||
La propiedad `maxContentLength` define el tamaño máximo de la respuesta en bytes. El adaptador HTTP de Node.js lo aplica en respuestas almacenadas en búfer y en streaming. El adaptador fetch lo aplica cuando la longitud de la respuesta está declarada, se puede rastrear el stream de respuesta o se puede determinar el tamaño de la respuesta.
|
||||
|
||||
> ⚠️ **Seguridad:** el valor por defecto es `-1` (sin límite). Las respuestas sin límite combinadas con la descompresión gzip/deflate/brotli/zstd permiten ataques de denegación de servicio por bomba de descompresión.
|
||||
> Establece un límite explícito al consumir servidores en los que no confíes plenamente.
|
||||
|
||||
### `maxBodyLength` <Badge type="warning" text="Solo en Node.js" />
|
||||
### `maxBodyLength` <Badge type="warning" text="HTTP Node.js/fetch" />
|
||||
|
||||
La propiedad `maxBodyLength` define el número máximo de bytes que el servidor aceptará en la solicitud.
|
||||
La propiedad `maxBodyLength` define el tamaño máximo del cuerpo de la solicitud en bytes. El adaptador HTTP de Node.js lo aplica, y el adaptador fetch lo aplica cuando se puede determinar la longitud del cuerpo de la solicitud.
|
||||
|
||||
### `redact`
|
||||
|
||||
|
||||
@@ -31,6 +31,20 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
Usa `axios.isCancel<T>()` para reducir los errores de cancelación a `CanceledError<T>`:
|
||||
|
||||
```ts
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
await axios.get<User>("/user?ID=12345", { signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (axios.isCancel<User>(error)) {
|
||||
handleCancellation(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Instancias e interceptores tipados
|
||||
|
||||
Anota el resultado de `axios.create` con `AxiosInstance`, y anota los interceptores de solicitud con `InternalAxiosRequestConfig` para obtener verificación de tipos de extremo a extremo en un cliente personalizado:
|
||||
|
||||
@@ -97,6 +97,7 @@ constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
|
||||
#### `set`
|
||||
|
||||
Ajoute un en-tête à l'objet d'en-têtes.
|
||||
Les noms d'en-têtes vides ou composés uniquement d'espaces sont ignorés.
|
||||
|
||||
```ts
|
||||
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
||||
|
||||
@@ -12,6 +12,8 @@ const instance = axios.create({
|
||||
|
||||
L'adaptateur supporte les mêmes fonctionnalités que l'adaptateur `xhr`, notamment la capture de la progression des envois et téléchargements. Il supporte également des types de réponse supplémentaires tels que `stream` et `formdata` (si l'environnement les prend en charge).
|
||||
|
||||
Lorsque `auth` est omis, l'adaptateur fetch peut lire les identifiants HTTP Basic depuis l'URL de requête, par exemple `https://user:pass@example.com`. Les identifiants d'URL encodés en pourcentage sont décodés avant la génération de l'en-tête `Authorization`, et `auth` prend le dessus sur les identifiants intégrés à l'URL.
|
||||
|
||||
## Fetch personnalisé <Badge type="tip" text="v1.12.0+" />
|
||||
|
||||
À partir de `v1.12.0`, vous pouvez personnaliser l'adaptateur fetch pour utiliser une fonction `fetch` personnalisée au lieu de celle de l'environnement global. Vous pouvez passer une fonction `fetch`, ainsi que des constructeurs `Request` et `Response` personnalisés via l'option de configuration `env`. Cela est utile lorsque vous travaillez avec des environnements personnalisés ou des frameworks d'application qui fournissent leur propre implémentation de `fetch`.
|
||||
|
||||
@@ -45,6 +45,8 @@ L'argument `rewrite` contrôle le comportement d'écrasement :
|
||||
|
||||
L'option peut également accepter une fonction définie par l'utilisateur qui détermine si la valeur doit être écrasée ou non. La fonction reçoit la valeur actuelle, le nom de l'en-tête et l'objet d'en-têtes comme arguments.
|
||||
|
||||
Les noms d'en-têtes vides ou composés uniquement d'espaces sont ignorés.
|
||||
|
||||
`AxiosHeaders` conserve la casse de la première clé correspondante qu'il voit. Vous pouvez utiliser cela pour préserver la casse spécifique d'un en-tête en initialisant une clé avec `undefined` puis en définissant les valeurs ultérieurement. Voir [Préserver la casse d'un en-tête spécifique](/pages/advanced/headers#preserving-a-specific-header-case).
|
||||
|
||||
## Get
|
||||
|
||||
@@ -9,6 +9,8 @@ formData.append('foo', 'bar');
|
||||
axios.post('https://httpbin.org/post', formData);
|
||||
```
|
||||
|
||||
Ne définissez pas manuellement l'en-tête `Content-Type` pour les objets `FormData` de navigateur, web worker ou React Native ; ces environnements ajoutent eux-mêmes la boundary multipart.
|
||||
|
||||
Dans Node.js, vous pouvez utiliser la bibliothèque `form-data` comme suit :
|
||||
|
||||
```js
|
||||
|
||||
@@ -119,8 +119,11 @@ Les `data` sont les données à envoyer comme corps de la requête. Il peut s'ag
|
||||
|
||||
- chaîne, objet simple, ArrayBuffer, ArrayBufferView, URLSearchParams
|
||||
- Navigateur uniquement : FormData, File, Blob
|
||||
- React Native : FormData
|
||||
- Node uniquement : Stream, Buffer, FormData (package form-data)
|
||||
|
||||
Pour les objets `FormData` de navigateur, web worker et React Native, ne définissez pas manuellement `Content-Type` ; l'environnement ajoute lui-même la boundary multipart.
|
||||
|
||||
Pour les objets `FormData` Node.js qui fournissent une méthode `getHeaders()`, axios copie tous les en-têtes retournés par défaut pour assurer la compatibilité avec la v1. Si l'objet `FormData` est personnalisé ou n'est pas pleinement de confiance, définissez `formDataHeaderPolicy: 'content-only'` pour ne copier que `Content-Type` et `Content-Length`, et définissez explicitement tout autre en-tête de requête via la configuration `headers` de la requête.
|
||||
|
||||
### `formDataHeaderPolicy` <Badge type="warning" text="Node.js uniquement" />
|
||||
@@ -231,16 +234,16 @@ La fonction `onUploadProgress` vous permet d'écouter la progression d'un envoi.
|
||||
|
||||
La fonction `onDownloadProgress` vous permet d'écouter la progression d'un téléchargement.
|
||||
|
||||
### `maxContentLength` <Badge type="warning" text="Node.js uniquement" />
|
||||
### `maxContentLength` <Badge type="warning" text="HTTP Node.js/fetch" />
|
||||
|
||||
La propriété `maxContentLength` définit le nombre maximum d'octets que le serveur acceptera dans la réponse.
|
||||
La propriété `maxContentLength` définit la taille maximale de la réponse en octets. L'adaptateur HTTP Node.js l'applique aux réponses mises en mémoire tampon et aux réponses streamées. L'adaptateur fetch l'applique lorsque la longueur de la réponse est déclarée, lorsque le stream de réponse peut être suivi ou lorsque la taille de la réponse peut être déterminée.
|
||||
|
||||
> ⚠️ **Sécurité :** la valeur par défaut est `-1` (illimitée). Des réponses non bornées combinées à la décompression gzip/deflate/brotli/zstd rendent possible un déni de service par bombe de décompression.
|
||||
> Définissez une limite explicite lorsque vous consommez des serveurs auxquels vous ne faites pas pleinement confiance.
|
||||
|
||||
### `maxBodyLength` <Badge type="warning" text="Node.js uniquement" />
|
||||
### `maxBodyLength` <Badge type="warning" text="HTTP Node.js/fetch" />
|
||||
|
||||
La propriété `maxBodyLength` définit le nombre maximum d'octets que le serveur acceptera dans la requête.
|
||||
La propriété `maxBodyLength` définit la taille maximale du corps de requête en octets. L'adaptateur HTTP Node.js l'applique, et l'adaptateur fetch l'applique lorsque la longueur du corps de requête peut être déterminée.
|
||||
|
||||
### `redact`
|
||||
|
||||
|
||||
@@ -31,6 +31,20 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
Utilisez `axios.isCancel<T>()` pour affiner les erreurs d'annulation en `CanceledError<T>` :
|
||||
|
||||
```ts
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
await axios.get<User>("/user?ID=12345", { signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (axios.isCancel<User>(error)) {
|
||||
handleCancellation(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Instances et intercepteurs typés
|
||||
|
||||
Annotez le résultat de `axios.create` avec `AxiosInstance`, et annotez les intercepteurs de requête avec `InternalAxiosRequestConfig` pour obtenir une vérification de types de bout en bout sur un client personnalisé :
|
||||
|
||||
@@ -97,6 +97,7 @@ constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
|
||||
#### `set`
|
||||
|
||||
Adds a header to the headers object.
|
||||
Empty or whitespace-only header names are ignored.
|
||||
|
||||
```ts
|
||||
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
||||
|
||||
@@ -12,6 +12,8 @@ const instance = axios.create({
|
||||
|
||||
The adapter supports the same functionality as the `xhr` adapter, including upload and download progress capturing. It also supports additional response types such as `stream` and `formdata` (if supported by the environment).
|
||||
|
||||
When `auth` is omitted, the fetch adapter can read HTTP Basic auth credentials from the request URL, for example `https://user:pass@example.com`. Percent-encoded URL credentials are decoded before the `Authorization` header is generated, and `auth` takes precedence over URL-embedded credentials.
|
||||
|
||||
## Custom fetch <Badge type="tip" text="v1.12.0+" />
|
||||
|
||||
Starting from `v1.12.0`, you can customise the fetch adapter to use a custom `fetch` function instead of the environment global. You can pass a custom `fetch` function, `Request`, and `Response` constructors via the `env` config option. This is useful when working with custom environments or app frameworks that provide their own `fetch` implementation.
|
||||
|
||||
@@ -45,6 +45,8 @@ The rewrite argument controls the overwriting behaviour:
|
||||
|
||||
The option can also accept a user-defined function that determines whether the value should be overwritten or not. The function receives the current value, header name, and the headers object as arguments.
|
||||
|
||||
Empty or whitespace-only header names are ignored.
|
||||
|
||||
`AxiosHeaders` keeps the case of the first matching key it sees. You can use this to preserve specific header casing by seeding a key with `undefined` and then setting values later. See [Preserving a specific header case](/pages/advanced/headers#preserving-a-specific-header-case).
|
||||
|
||||
## Get
|
||||
|
||||
@@ -9,6 +9,8 @@ formData.append('foo', 'bar');
|
||||
axios.post('https://httpbin.org/post', formData);
|
||||
```
|
||||
|
||||
Do not manually set the `Content-Type` header for browser, web worker, or React Native `FormData`; those runtimes add the multipart boundary themselves.
|
||||
|
||||
In node.js, you can use the `form-data` library as follows:
|
||||
|
||||
```js
|
||||
|
||||
@@ -119,8 +119,11 @@ The `data` is the data to be sent as the request body. This can be a string, a p
|
||||
|
||||
- string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
|
||||
- Browser only: FormData, File, Blob
|
||||
- React Native: FormData
|
||||
- Node only: Stream, Buffer, FormData (form-data package)
|
||||
|
||||
For browser, web worker, and React Native `FormData`, do not manually set `Content-Type`; the runtime adds the multipart boundary.
|
||||
|
||||
For Node.js `FormData` objects that provide a `getHeaders()` method, axios copies all returned headers by default for v1 compatibility. If the `FormData` object is custom or not fully trusted, set `formDataHeaderPolicy: 'content-only'` to copy only `Content-Type` and `Content-Length`, and set any other request headers explicitly via the request `headers` config.
|
||||
|
||||
### `formDataHeaderPolicy` <Badge type="warning" text="Node.js only" />
|
||||
@@ -231,16 +234,16 @@ The `onUploadProgress` function allows you to listen to the progress of an uploa
|
||||
|
||||
The `onDownloadProgress` function allows you to listen to the progress of a download.
|
||||
|
||||
### `maxContentLength` <Badge type="warning" text="Node.js only" />
|
||||
### `maxContentLength` <Badge type="warning" text="Node.js HTTP/fetch adapter" />
|
||||
|
||||
The `maxContentLength` property defines the maximum number of bytes that the server will accept in the response.
|
||||
The `maxContentLength` property defines the maximum response size in bytes. The Node.js HTTP adapter enforces it for buffered and streamed responses. The fetch adapter enforces it when the response length is declared, the response stream can be tracked, or the response size can otherwise be determined.
|
||||
|
||||
> ⚠️ **Security:** defaults to `-1` (unlimited). Unbounded responses combined with gzip/deflate/brotli/zstd decompression allow decompression-bomb DoS.
|
||||
> Set an explicit limit when requesting servers you do not fully trust.
|
||||
|
||||
### `maxBodyLength` <Badge type="warning" text="Node.js only" />
|
||||
### `maxBodyLength` <Badge type="warning" text="Node.js HTTP/fetch adapter" />
|
||||
|
||||
The `maxBodyLength` property defines the maximum number of bytes that the server will accept in the request.
|
||||
The `maxBodyLength` property defines the maximum request body size in bytes. The Node.js HTTP adapter enforces it, and the fetch adapter enforces it when the request body length can be determined.
|
||||
|
||||
### `redact`
|
||||
|
||||
|
||||
@@ -31,6 +31,20 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
Use `axios.isCancel<T>()` to narrow cancellation errors to `CanceledError<T>`:
|
||||
|
||||
```ts
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
await axios.get<User>("/user?ID=12345", { signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (axios.isCancel<User>(error)) {
|
||||
handleCancellation(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Typed instances and interceptors
|
||||
|
||||
Annotate the result of `axios.create` with `AxiosInstance`, and annotate request interceptors with `InternalAxiosRequestConfig` to get end-to-end type checking on a custom client:
|
||||
|
||||
@@ -97,6 +97,7 @@ constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
|
||||
#### `set`
|
||||
|
||||
向请求头对象添加一个请求头。
|
||||
空字符串或仅包含空白字符的请求头名称会被忽略。
|
||||
|
||||
```ts
|
||||
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
||||
|
||||
@@ -12,6 +12,8 @@ const instance = axios.create({
|
||||
|
||||
该适配器支持与 `xhr` 适配器相同的功能,包括上传和下载进度捕获,还支持额外的响应类型,如 `stream` 和 `formdata`(如果环境支持)。
|
||||
|
||||
当省略 `auth` 时,fetch 适配器可以从请求 URL 中读取 HTTP Basic 认证凭据,例如 `https://user:pass@example.com`。生成 `Authorization` 请求头前会先解码 URL 中经过百分号编码的凭据,并且 `auth` 优先于 URL 中的凭据。
|
||||
|
||||
## 自定义 fetch <Badge type="tip" text="v1.12.0+" />
|
||||
|
||||
从 `v1.12.0` 起,你可以自定义 fetch 适配器,使用自定义的 `fetch` 函数代替环境全局的 `fetch`。可以通过 `env` 配置选项传入自定义的 `fetch` 函数、`Request` 和 `Response` 构造函数。这在使用提供了自己 `fetch` 实现的自定义环境或应用框架时非常实用。
|
||||
|
||||
@@ -45,6 +45,8 @@ set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean);
|
||||
|
||||
该参数也可以接受一个用户自定义函数,用于决定是否应覆盖该值,函数接收当前值、请求头名称和请求头对象作为参数。
|
||||
|
||||
空字符串或仅包含空白字符的请求头名称会被忽略。
|
||||
|
||||
`AxiosHeaders` 会保留第一个匹配键的大小写形式。你可以利用这一特性,先以 `undefined` 值预设一个键名,之后再设置值,从而保留特定的请求头大小写。详见[保留特定请求头大小写](/pages/advanced/headers#preserving-a-specific-header-case)。
|
||||
|
||||
## Get
|
||||
|
||||
@@ -9,6 +9,8 @@ formData.append('foo', 'bar');
|
||||
axios.post('https://httpbin.org/post', formData);
|
||||
```
|
||||
|
||||
对于浏览器、Web Worker 或 React Native 的 `FormData`,不要手动设置 `Content-Type` 请求头;这些运行时会自行添加 multipart boundary。
|
||||
|
||||
在 Node.js 中,可以使用 `form-data` 库,如下所示:
|
||||
|
||||
```js
|
||||
|
||||
@@ -119,8 +119,11 @@ const client = axios.create({
|
||||
|
||||
- string、普通对象、ArrayBuffer、ArrayBufferView、URLSearchParams
|
||||
- 仅浏览器:FormData、File、Blob
|
||||
- React Native:FormData
|
||||
- 仅 Node.js:Stream、Buffer、FormData(form-data 包)
|
||||
|
||||
对于浏览器、Web Worker 和 React Native 的 `FormData`,不要手动设置 `Content-Type`;运行时会自行添加 multipart boundary。
|
||||
|
||||
对于提供了 `getHeaders()` 方法的 Node.js `FormData` 对象,axios 默认会复制其返回的所有请求头,以保持 v1 兼容性。如果 `FormData` 对象是自定义的或不完全可信,可设置 `formDataHeaderPolicy: 'content-only'`,仅复制 `Content-Type` 和 `Content-Length`,其他请求头则通过请求 `headers` 配置显式设置。
|
||||
|
||||
### `formDataHeaderPolicy` <Badge type="warning" text="仅 Node.js" />
|
||||
@@ -231,16 +234,16 @@ axios.get('/user', { withCredentials: true, withXSRFToken: true });
|
||||
|
||||
`onDownloadProgress` 函数允许你监听下载进度。
|
||||
|
||||
### `maxContentLength` <Badge type="warning" text="仅 Node.js" />
|
||||
### `maxContentLength` <Badge type="warning" text="Node.js HTTP/fetch" />
|
||||
|
||||
`maxContentLength` 属性定义服务器在响应中允许接收的最大字节数。
|
||||
`maxContentLength` 属性定义响应内容允许的最大字节数。Node.js HTTP 适配器会对缓冲响应和流式响应执行该限制。fetch 适配器会在响应声明了长度、响应流可跟踪,或响应大小可确定时执行该限制。
|
||||
|
||||
> ⚠️ **安全提示:** 默认值为 `-1`(不限制)。响应不加限制再加上 gzip/deflate/brotli/zstd 解压,会带来解压炸弹导致的拒绝服务风险。
|
||||
> 在访问不完全可信的服务器时,请显式设置该限制。
|
||||
|
||||
### `maxBodyLength` <Badge type="warning" text="仅 Node.js" />
|
||||
### `maxBodyLength` <Badge type="warning" text="Node.js HTTP/fetch" />
|
||||
|
||||
`maxBodyLength` 属性定义服务器在请求中允许接收的最大字节数。
|
||||
`maxBodyLength` 属性定义请求体允许的最大字节数。Node.js HTTP 适配器会执行该限制;fetch 适配器会在请求体长度可确定时执行该限制。
|
||||
|
||||
### `redact`
|
||||
|
||||
|
||||
@@ -31,6 +31,20 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
使用 `axios.isCancel<T>()` 可以将取消错误收窄为 `CanceledError<T>`:
|
||||
|
||||
```ts
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
await axios.get<User>("/user?ID=12345", { signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (axios.isCancel<User>(error)) {
|
||||
handleCancellation(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 带类型的实例与拦截器
|
||||
|
||||
将 `axios.create` 的结果标注为 `AxiosInstance`,并将请求拦截器标注为 `InternalAxiosRequestConfig`,即可对自定义客户端实现端到端的类型检查:
|
||||
|
||||
Reference in New Issue
Block a user