Skip to content

Commit

Permalink
chore(docs): added AxiosHeaders docs; (#5932)
Browse files Browse the repository at this point in the history
  • Loading branch information
DigitalBrainJS committed Sep 30, 2023
1 parent a1c8ad0 commit a48a63a
Showing 1 changed file with 255 additions and 0 deletions.
255 changes: 255 additions & 0 deletions README.md
Expand Up @@ -66,6 +66,7 @@
- [HTML Form Posting](#-html-form-posting-browser)
- [🆕 Progress capturing](#-progress-capturing)
- [🆕 Rate limiting](#-progress-capturing)
- [🆕 AxiosHeaders](#-axiosheaders)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)
Expand Down Expand Up @@ -1291,6 +1292,260 @@ const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, {
});
```
## 🆕 AxiosHeaders
Axios has its own `AxiosHeaders` class to manipulate headers using a Map-like API that guarantees caseless work.
Although HTTP is case-insensitive in headers, Axios will retain the case of the original header for stylistic reasons
and for a workaround when servers mistakenly consider the header's case.
The old approach of directly manipulating headers object is still available, but deprecated and not recommended for future usage.
### Working with headers
An AxiosHeaders object instance can contain different types of internal values. that control setting and merging logic.
The final headers object with string values is obtained by Axios by calling the `toJSON` method.
> Note: By JSON here we mean an object consisting only of string values intended to be sent over the network.
The header value can be one of the following types:
- `string` - normal string value that will be sent to the server
- `null` - skip header when rendering to JSON
- `false` - skip header when rendering to JSON, additionally indicates that `set` method must be called with `rewrite` option set to `true`
to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`)
- `undefined` - value is not set
> Note: The header value is considered set if it is not equal to undefined.
The headers object is always initialized inside interceptors and transformers:
```ts
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
request.headers.set('My-header', 'value');

request.headers.set({
"My-set-header1": "my-set-value1",
"My-set-header2": "my-set-value2"
});

request.headers.set('User-Agent', false); // disable subsequent setting the header by Axios

request.headers.setContentType('text/plain');

request.headers['My-set-header2'] = 'newValue' // direct access is deprecated

return request;
}
);
````

You can iterate over an `AxiosHeaders` instance using a `for...of` statement:

````js
const headers = new AxiosHeaders({
foo: '1',
bar: '2',
baz: '3'
});

for(const [header, value] of headers) {
console.log(header, value);
}

// foo 1
// bar 2
// baz 3
````

### new AxiosHeaders(headers?)

Constructs a new `AxiosHeaders` instance.

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

If the headers object is a string, it will be parsed as RAW HTTP headers.

````js
const headers = new AxiosHeaders(`
Host: www.bing.com
User-Agent: curl/7.54.0
Accept: */*`);

console.log(headers);

// Object [AxiosHeaders] {
// host: 'www.bing.com',
// 'user-agent': 'curl/7.54.0',
// accept: '*/*'
// }
````

### AxiosHeaders#set

```ts
set(headerName, value: Axios, rewrite?: boolean);
set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean);
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean);
```

The `rewrite` argument controls the overwriting behavior:
- `false` - do not overwrite if header's value is set (is not `undefined`)
- `undefined` (default) - overwrite the header unless its value is set to `false`
- `true` - rewrite anyway
The option can also accept a user-defined function that determines whether the value should be overwritten or not.
Returns `this`.
### AxiosHeaders#get(header)
```
get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
````
Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`,
matcher function or internal key-value parser.

```ts
const headers = new AxiosHeaders({
'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h'
});

console.log(headers.get('Content-Type'));
// multipart/form-data; boundary=Asrf456BGe4h

console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters:
// [Object: null prototype] {
// 'multipart/form-data': undefined,
// boundary: 'Asrf456BGe4h'
// }


console.log(headers.get('Content-Type', (value, name, headers) => {
return String(value).replace(/a/g, 'ZZZ');
}));
// multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h

console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]);
// boundary=Asrf456BGe4h

```
Returns the value of the header.
### AxiosHeaders#has(header, matcher?)
```
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
```
Returns `true` if the header is set (has no `undefined` value).
### AxiosHeaders#delete(header, matcher?)
```
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
```
Returns `true` if at least one header has been removed.
### AxiosHeaders#clear(matcher?)
```
clear(matcher?: AxiosHeaderMatcher): boolean;
```
Removes all headers.
Unlike the `delete` method matcher, this optional matcher will be used to match against the header name rather than the value.
```ts
const headers = new AxiosHeaders({
'foo': '1',
'x-foo': '2',
'x-bar': '3',
});

console.log(headers.clear(/^x-/)); // true

console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' }
```
Returns `true` if at least one header has been cleared.
### AxiosHeaders#normalize(format);
If the headers object was changed directly, it can have duplicates with the same name but in different cases.
This method normalizes the headers object by combining duplicate keys into one.
Axios uses this method internally after calling each interceptor.
Set `format` to true for converting headers name to lowercase and capitalize the initial letters (`cOntEnt-type` => `Content-Type`)
```js
const headers = new AxiosHeaders({
'foo': '1',
});

headers.Foo = '2';
headers.FOO = '3';

console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' }
console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' }
console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' }
```
Returns `this`.
### AxiosHeaders#concat(...targets)
```
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
```
Merges the instance with targets into a new `AxiosHeaders` instance. If the target is a string, it will be parsed as RAW HTTP headers.
Returns a new `AxiosHeaders` instance.
### AxiosHeaders#toJSON(asStrings?)
````
toJSON(asStrings?: boolean): RawAxiosHeaders;
````
Resolve all internal headers values into a new null prototype object.
Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas.
### AxiosHeaders.from(thing?)
````
from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
````
Returns a new `AxiosHeaders` instance created from the raw headers passed in,
or simply returns the given headers object if it's an `AxiosHeaders` instance.
### AxiosHeaders.concat(...targets)
````
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
````
Returns a new `AxiosHeaders` instance created by merging the target objects.
### Shortcuts
The following shortcuts are available:
- `setContentType`, `getContentType`, `hasContentType`
- `setContentLength`, `getContentLength`, `hasContentLength`
- `setAccept`, `getAccept`, `hasAccept`
- `setUserAgent`, `getUserAgent`, `hasUserAgent`
- `setContentEncoding`, `getContentEncoding`, `hasContentEncoding`
## Semver
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
Expand Down

0 comments on commit a48a63a

Please sign in to comment.