2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-17 19:21:29 +03:00

docs: document paramsSerializer.encode for strict RFC 3986 query encoding (#10809) (#10821)

* docs: document paramsSerializer.encode for strict RFC 3986 query encoding

Fixes #10809

Add a subsection to request-config.md explaining how to use the encode
option with encodeURIComponent for backends that require strict
percent-encoding of query values.

The default axios encoder decodes %3A, %24, %2C and %20 for readability,
which is correct per RFC 3986 but can cause issues with stricter backends.
This documents the existing `paramsSerializer.encode` escape hatch.

* chore: improve documentation

---------

Co-authored-by: mixelburg <mixelburg@gmail.com>
Co-authored-by: Jason Saayman <jasonsaayman@gmail.com>
This commit is contained in:
mixelburg
2026-04-30 19:19:03 +03:00
committed by GitHub
parent 0fe3a5fc14
commit 79f39e1d04
5 changed files with 95 additions and 0 deletions
+19
View File
@@ -1004,6 +1004,25 @@ These are the available config options for making requests. Only the `url` is re
}
```
### Strict RFC 3986 percent-encoding for query params
By default, axios decodes `%3A`, `%24`, `%2C` and `%20` back to `:`, `$`, `,` and `+` for readability (the `+` follows the `application/x-www-form-urlencoded` convention for spaces in query strings). These characters are valid in a query component under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), so the default output is correct, but some backends require strict percent-encoding and reject the readable form.
Override the default encoder via `paramsSerializer.encode`:
```js
// Per-request: emit strict RFC 3986 percent-encoding for query values
axios.get('/foo', {
params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
paramsSerializer: { encode: encodeURIComponent }
});
// Or set it on the instance defaults
const client = axios.create({
paramsSerializer: { encode: encodeURIComponent }
});
```
## 🔥 HTTP/2 Support
Axios has experimental HTTP/2 support available via the Node.js HTTP adapter.
+19
View File
@@ -38,6 +38,25 @@ Los `params` son los parámetros de URL que se enviarán con la solicitud. Debe
La función `paramsSerializer` te permite serializar el objeto `params` antes de enviarlo al servidor. Hay varias opciones disponibles para esta función; consulta el ejemplo completo de configuración de solicitud al final de esta página.
#### Codificación porcentual estricta RFC 3986
De forma predeterminada, axios decodifica `%3A`, `%24`, `%2C` y `%20` de vuelta a `:`, `$`, `,` y `+` por legibilidad (el `+` sigue la convención `application/x-www-form-urlencoded` para representar un espacio en una cadena de consulta). Estos caracteres son válidos dentro de un componente de consulta según la [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), por lo que la salida predeterminada es correcta. Sin embargo, algunos backends requieren codificación porcentual estricta y rechazan la forma legible.
Usa la opción `encode` para sobrescribir el codificador predeterminado:
```js
// Por solicitud: emitir codificación porcentual estricta RFC 3986 para los valores de consulta
axios.get('/foo', {
params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
paramsSerializer: { encode: encodeURIComponent }
});
// O establecerlo en los valores predeterminados de la instancia
const client = axios.create({
paramsSerializer: { encode: encodeURIComponent }
});
```
### `data`
El `data` son los datos que se enviarán como cuerpo de la solicitud. Puede ser una cadena de texto, un objeto plano, un Buffer, ArrayBuffer, FormData, Stream o URLSearchParams. Solo aplica para los métodos de solicitud `PUT`, `POST`, `DELETE` y `PATCH`. Cuando no se establece `transformRequest`, debe ser de uno de los siguientes tipos:
+19
View File
@@ -38,6 +38,25 @@ Les `params` sont les paramètres d'URL à envoyer avec la requête. Il doit s'a
La fonction `paramsSerializer` vous permet de sérialiser l'objet `params` avant son envoi au serveur. Plusieurs options sont disponibles pour cette fonction ; veuillez vous référer à l'exemple de configuration complète en bas de cette page.
#### Encodage pour-cent strict RFC 3986
Par défaut, axios redécode `%3A`, `%24`, `%2C` et `%20` vers `:`, `$`, `,` et `+` pour la lisibilité (le `+` suit la convention `application/x-www-form-urlencoded` pour représenter une espace dans une chaîne de requête). Ces caractères sont valides dans un composant de requête selon la [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), donc la sortie par défaut est correcte. Cependant, certains backends exigent un encodage pour-cent strict et rejettent la forme lisible.
Utilisez l'option `encode` pour remplacer l'encodeur par défaut :
```js
// Par requête : émettre un encodage pour-cent strict RFC 3986 pour les valeurs de requête
axios.get('/foo', {
params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
paramsSerializer: { encode: encodeURIComponent }
});
// Ou définir cela sur les valeurs par défaut de l'instance
const client = axios.create({
paramsSerializer: { encode: encodeURIComponent }
});
```
### `data`
Les `data` sont les données à envoyer comme corps de la requête. Il peut s'agir d'une chaîne, d'un objet simple, d'un Buffer, d'un ArrayBuffer, d'un FormData, d'un Stream ou d'un URLSearchParams. Ne s'applique que pour les méthodes de requête `PUT`, `POST`, `DELETE` et `PATCH`. Sans `transformRequest`, doit être de l'un des types suivants :
+19
View File
@@ -81,6 +81,25 @@ The `params` are the URL parameters to be sent with the request. This must be a
The `paramsSerializer` function allows you to serialize the `params` object before it is sent to the server. There are a few options available for this function, so please refer to the full request config example at the end of this page.
#### Strict RFC 3986 percent-encoding
By default, axios decodes `%3A`, `%24`, `%2C` and `%20` back to `:`, `$`, `,` and `+` for readability (the `+` follows the `application/x-www-form-urlencoded` convention for spaces in query strings). These characters are valid in a query component under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), so the default output is correct. However, some backends require strict percent-encoding and reject the readable form.
Use the `encode` option to override the default encoder:
```js
// Per-request: emit strict RFC 3986 percent-encoding for query values
axios.get('/foo', {
params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
paramsSerializer: { encode: encodeURIComponent }
});
// Or set it on the instance defaults
const client = axios.create({
paramsSerializer: { encode: encodeURIComponent }
});
```
### `data`
The `data` is the data to be sent as the request body. This can be a string, a plain object, a Buffer, ArrayBuffer, FormData, Stream, or URLSearchParams. Only applicable for request methods `PUT`, `POST`, `DELETE` , and `PATCH`. When no `transformRequest` is set, must be of one of the following types:
+19
View File
@@ -38,6 +38,25 @@
`paramsSerializer` 函数允许你在参数发送到服务器之前自定义 `params` 对象的序列化方式,有多个可用选项,详见本页末尾的完整请求配置示例。
#### 严格的 RFC 3986 百分号编码
axios 默认会将 `%3A``%24``%2C``%20` 解码回 `:``$``,``+`,以提升可读性(其中 `+` 遵循查询字符串中表示空格的 `application/x-www-form-urlencoded` 约定)。这些字符在 [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4) 中对查询组件而言都是合法的,因此默认输出是正确的。但部分后端要求严格的百分号编码,会拒绝这种可读形式。
可通过 `encode` 选项覆盖默认编码器:
```js
// 单次请求:对查询值使用严格的 RFC 3986 百分号编码
axios.get('/foo', {
params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
paramsSerializer: { encode: encodeURIComponent }
});
// 也可在实例默认值中设置
const client = axios.create({
paramsSerializer: { encode: encodeURIComponent }
});
```
### `data`
`data` 是作为请求体发送的数据,可以是字符串、普通对象、Buffer、ArrayBuffer、FormData、Stream 或 URLSearchParams,仅适用于 `PUT``POST``DELETE``PATCH` 请求方法。在未设置 `transformRequest` 的情况下,必须是以下类型之一: