npm-axios

Description
Promise based HTTP client for the browser and node.js
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-axios@1.6.0

headers-management.md docs/

1
# Headers Management
2
3
Sophisticated HTTP headers management with the AxiosHeaders class providing type-safe header operations, automatic normalization, and convenient methods for common headers.
4
5
## Capabilities
6
7
### AxiosHeaders Class
8
9
Comprehensive HTTP headers management class with type-safe operations.
10
11
```typescript { .api }
12
class AxiosHeaders {
13
/**
14
* Creates new AxiosHeaders instance
15
* @param headers - Initial headers (object, string, or AxiosHeaders)
16
*/
17
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
18
19
/** Index signature for dynamic header access */
20
[key: string]: any;
21
22
/**
23
* Set header value(s)
24
* @param headerName - Header name
25
* @param value - Header value
26
* @param rewrite - Whether to overwrite existing header
27
* @returns AxiosHeaders instance for chaining
28
*/
29
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
30
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
31
32
/**
33
* Get header value
34
* @param headerName - Header name
35
* @param parser - RegExp for parsing header value
36
* @returns Parsed header value or null
37
*/
38
get(headerName: string, parser: RegExp): RegExpExecArray | null;
39
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
40
41
/**
42
* Check if header exists
43
* @param header - Header name
44
* @param matcher - Optional matcher function
45
* @returns Whether header exists
46
*/
47
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
48
49
/**
50
* Delete header(s)
51
* @param header - Header name(s) to delete
52
* @param matcher - Optional matcher function
53
* @returns Whether any headers were deleted
54
*/
55
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
56
57
/**
58
* Clear headers matching criteria
59
* @param matcher - Optional matcher function
60
* @returns Whether any headers were cleared
61
*/
62
clear(matcher?: AxiosHeaderMatcher): boolean;
63
64
/**
65
* Normalize header names
66
* @param format - Whether to format header names
67
* @returns AxiosHeaders instance
68
*/
69
normalize(format: boolean): AxiosHeaders;
70
71
/**
72
* Concatenate with other headers
73
* @param targets - Headers to concatenate
74
* @returns New AxiosHeaders instance
75
*/
76
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
77
78
/**
79
* Convert to plain object
80
* @param asStrings - Whether to convert all values to strings
81
* @returns Plain object representation
82
*/
83
toJSON(asStrings?: boolean): RawAxiosHeaders;
84
85
/**
86
* Create AxiosHeaders from various inputs
87
* @param thing - Input to convert
88
* @returns New AxiosHeaders instance
89
*/
90
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
91
92
/**
93
* Create header accessor
94
* @param header - Header name(s)
95
* @returns AxiosHeaders instance
96
*/
97
static accessor(header: string | string[]): AxiosHeaders;
98
99
/**
100
* Concatenate multiple header sources
101
* @param targets - Headers to concatenate
102
* @returns New AxiosHeaders instance
103
*/
104
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
105
106
/** Iterator for header entries */
107
[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;
108
}
109
110
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
111
112
type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);
113
114
type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;
115
116
interface RawAxiosHeaders {
117
[key: string]: AxiosHeaderValue;
118
}
119
```
120
121
**Usage Examples:**
122
123
```typescript
124
import { AxiosHeaders } from "axios";
125
126
// Create headers from object
127
const headers = new AxiosHeaders({
128
"Content-Type": "application/json",
129
"Authorization": "Bearer token123",
130
"X-Custom-Header": "value"
131
});
132
133
// Create from string (HTTP header format)
134
const headersFromString = new AxiosHeaders(`
135
Content-Type: application/json
136
Authorization: Bearer token123
137
X-Custom-Header: value
138
`);
139
140
// Set individual headers
141
headers.set("User-Agent", "MyApp/1.0.0");
142
headers.set("Accept", "application/json, text/plain");
143
144
// Set multiple headers at once
145
headers.set({
146
"Cache-Control": "no-cache",
147
"X-Requested-With": "XMLHttpRequest"
148
});
149
150
// Get header values
151
console.log(headers.get("Content-Type")); // "application/json"
152
console.log(headers.get("authorization")); // "Bearer token123" (case-insensitive)
153
154
// Check if header exists
155
console.log(headers.has("Content-Type")); // true
156
console.log(headers.has("X-Nonexistent")); // false
157
158
// Delete headers
159
headers.delete("X-Custom-Header");
160
headers.delete(["Cache-Control", "X-Requested-With"]);
161
162
// Convert to plain object
163
const plainHeaders = headers.toJSON();
164
console.log(plainHeaders);
165
```
166
167
### Common Header Methods
168
169
Convenient methods for working with standard HTTP headers.
170
171
```typescript { .api }
172
// Content-Type methods
173
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
174
getContentType(parser?: RegExp): RegExpExecArray | null;
175
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
176
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
177
178
// Content-Length methods
179
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
180
getContentLength(parser?: RegExp): RegExpExecArray | null;
181
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
182
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
183
184
// Accept methods
185
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
186
getAccept(parser?: RegExp): RegExpExecArray | null;
187
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
188
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
189
190
// User-Agent methods
191
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
192
getUserAgent(parser?: RegExp): RegExpExecArray | null;
193
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
194
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
195
196
// Content-Encoding methods
197
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
198
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
199
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
200
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
201
202
// Authorization methods
203
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
204
getAuthorization(parser?: RegExp): RegExpExecArray | null;
205
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
206
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
207
208
type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
import { AxiosHeaders } from "axios";
215
216
const headers = new AxiosHeaders();
217
218
// Content-Type methods
219
headers.setContentType("application/json");
220
console.log(headers.getContentType()); // "application/json"
221
console.log(headers.hasContentType()); // true
222
223
// Authorization methods
224
headers.setAuthorization("Bearer token123");
225
console.log(headers.getAuthorization()); // "Bearer token123"
226
227
// User-Agent methods
228
headers.setUserAgent("MyApp/1.0.0 (Windows NT 10.0)");
229
console.log(headers.getUserAgent()); // "MyApp/1.0.0 (Windows NT 10.0)"
230
231
// Accept methods
232
headers.setAccept("application/json, text/plain, */*");
233
console.log(headers.getAccept()); // "application/json, text/plain, */*"
234
235
// Content-Encoding methods
236
headers.setContentEncoding("gzip");
237
console.log(headers.getContentEncoding()); // "gzip"
238
239
// Content-Length methods
240
headers.setContentLength("1024");
241
console.log(headers.getContentLength()); // "1024"
242
243
// Parse header values with RegExp
244
const authValue = headers.getAuthorization(/Bearer (.+)/);
245
if (authValue) {
246
console.log("Token:", authValue[1]); // "token123"
247
}
248
```
249
250
### Header Concatenation and Merging
251
252
Combine headers from multiple sources with proper handling of duplicates.
253
254
**Usage Examples:**
255
256
```typescript
257
import { AxiosHeaders } from "axios";
258
259
// Create base headers
260
const baseHeaders = new AxiosHeaders({
261
"User-Agent": "MyApp/1.0.0",
262
"Accept": "application/json"
263
});
264
265
// Create additional headers
266
const authHeaders = new AxiosHeaders({
267
"Authorization": "Bearer token123",
268
"X-Client-Version": "1.0.0"
269
});
270
271
// Concatenate headers
272
const combinedHeaders = baseHeaders.concat(authHeaders, {
273
"Content-Type": "application/json",
274
"X-Request-ID": "req-123"
275
});
276
277
console.log(combinedHeaders.toJSON());
278
// {
279
// "User-Agent": "MyApp/1.0.0",
280
// "Accept": "application/json",
281
// "Authorization": "Bearer token123",
282
// "X-Client-Version": "1.0.0",
283
// "Content-Type": "application/json",
284
// "X-Request-ID": "req-123"
285
// }
286
287
// Static concatenation
288
const mergedHeaders = AxiosHeaders.concat(
289
{ "Accept": "application/json" },
290
{ "Content-Type": "application/json" },
291
"Authorization: Bearer token\nX-Custom: value"
292
);
293
294
// Create from various sources
295
const headers1 = AxiosHeaders.from({ "Content-Type": "application/json" });
296
const headers2 = AxiosHeaders.from("Authorization: Bearer token");
297
const headers3 = AxiosHeaders.from(headers1);
298
```
299
300
### Header Iteration and Processing
301
302
Iterate through headers and process them programmatically.
303
304
**Usage Examples:**
305
306
```typescript
307
import { AxiosHeaders } from "axios";
308
309
const headers = new AxiosHeaders({
310
"Content-Type": "application/json",
311
"Authorization": "Bearer token123",
312
"X-Custom-Header": "value",
313
"Accept": "application/json"
314
});
315
316
// Iterate through headers
317
for (const [name, value] of headers) {
318
console.log(`${name}: ${value}`);
319
}
320
321
// Convert to array of entries
322
const entries = Array.from(headers);
323
console.log(entries);
324
// [
325
// ["Content-Type", "application/json"],
326
// ["Authorization", "Bearer token123"],
327
// ["X-Custom-Header", "value"],
328
// ["Accept", "application/json"]
329
// ]
330
331
// Filter headers
332
const customHeaders = new AxiosHeaders();
333
for (const [name, value] of headers) {
334
if (name.startsWith("X-")) {
335
customHeaders.set(name, value);
336
}
337
}
338
339
// Process headers with Array methods
340
const headerNames = Array.from(headers).map(([name]) => name);
341
console.log("Header names:", headerNames);
342
343
const hasAuthHeader = Array.from(headers).some(([name]) =>
344
name.toLowerCase() === "authorization"
345
);
346
console.log("Has auth header:", hasAuthHeader);
347
```
348
349
### Header Normalization and Formatting
350
351
Normalize header names and values for consistency.
352
353
**Usage Examples:**
354
355
```typescript
356
import { AxiosHeaders } from "axios";
357
358
// Headers with inconsistent casing
359
const headers = new AxiosHeaders({
360
"content-type": "application/json",
361
"AUTHORIZATION": "Bearer token123",
362
"X-custom-HEADER": "value"
363
});
364
365
// Normalize headers (axios does this automatically)
366
const normalized = headers.normalize(true);
367
368
console.log(normalized.toJSON());
369
// Headers are normalized to proper casing:
370
// {
371
// "Content-Type": "application/json",
372
// "Authorization": "Bearer token123",
373
// "X-Custom-Header": "value"
374
// }
375
376
// Clear headers with matcher
377
headers.clear((value, name) => name.startsWith("X-"));
378
379
// Delete headers with matcher
380
headers.delete("authorization", (value, name) =>
381
name.toLowerCase() === "authorization"
382
);
383
384
// Set header with conditional rewrite
385
headers.set("Content-Type", "text/plain", (value, name) =>
386
value !== "application/json"
387
);
388
```
389
390
### Request and Response Header Types
391
392
Type definitions for request and response headers with common header names.
393
394
```typescript { .api }
395
type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {
396
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
397
} & {
398
'Content-Type': ContentType
399
}>;
400
401
type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
402
403
type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
404
405
type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
406
407
type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization';
408
409
type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control' | 'Content-Encoding';
410
411
type RawCommonResponseHeaders = {
412
[Key in CommonResponseHeadersList]: AxiosHeaderValue;
413
} & {
414
"set-cookie": string[];
415
};
416
```
417
418
**Usage Examples:**
419
420
```typescript
421
import axios, { AxiosRequestHeaders, AxiosResponseHeaders } from "axios";
422
423
// Typed request headers
424
const requestHeaders: AxiosRequestHeaders = new AxiosHeaders({
425
"Accept": "application/json",
426
"Content-Type": "application/json",
427
"Authorization": "Bearer token123",
428
"User-Agent": "MyApp/1.0.0"
429
});
430
431
// Use in request
432
const response = await axios.post("https://api.example.com/data",
433
{ message: "Hello" },
434
{ headers: requestHeaders }
435
);
436
437
// Access response headers
438
const responseHeaders: AxiosResponseHeaders = response.headers;
439
console.log(responseHeaders["content-type"]);
440
console.log(responseHeaders["cache-control"]);
441
console.log(responseHeaders["set-cookie"]); // Array of cookie strings
442
443
// Type-safe header access
444
if (responseHeaders instanceof AxiosHeaders) {
445
console.log(responseHeaders.getContentType());
446
console.log(responseHeaders.getContentLength());
447
}
448
```