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.11.0

headers.md docs/

1
# Headers Management
2
3
Advanced header manipulation with type-safe operations, automatic content-type handling, and specialized methods for common HTTP headers.
4
5
## Capabilities
6
7
### AxiosHeaders Class
8
9
Powerful header management class with advanced manipulation methods and type safety.
10
11
```javascript { .api }
12
/**
13
* Advanced headers management class
14
*/
15
class AxiosHeaders {
16
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
17
18
/** Allow bracket notation access */
19
[key: string]: any;
20
21
/** Set header value with optional rewrite control */
22
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
23
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
24
25
/** Get header value with optional parsing */
26
get(headerName: string, parser: RegExp): RegExpExecArray | null;
27
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
28
29
/** Check if header exists */
30
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
31
32
/** Delete header(s) */
33
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
34
35
/** Clear headers matching criteria */
36
clear(matcher?: AxiosHeaderMatcher): boolean;
37
38
/** Normalize header names */
39
normalize(format: boolean): AxiosHeaders;
40
41
/** Concatenate with other headers */
42
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
43
44
/** Convert to plain object */
45
toJSON(asStrings?: boolean): RawAxiosHeaders;
46
}
47
48
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
49
type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);
50
type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;
51
```
52
53
**Usage Examples:**
54
55
```javascript
56
import { AxiosHeaders } from "axios";
57
58
// Create headers from object
59
const headers = new AxiosHeaders({
60
"Content-Type": "application/json",
61
"Authorization": "Bearer token123"
62
});
63
64
// Set individual headers
65
headers.set("X-Custom-Header", "custom-value");
66
headers.set("Accept", "application/json");
67
68
// Set multiple headers at once
69
headers.set({
70
"User-Agent": "MyApp/1.0",
71
"X-API-Version": "v2"
72
});
73
74
// Get header values
75
const contentType = headers.get("Content-Type");
76
const auth = headers.get("authorization"); // Case-insensitive
77
78
// Check if header exists
79
if (headers.has("Authorization")) {
80
console.log("Auth header is present");
81
}
82
83
// Delete headers
84
headers.delete("X-Temporary-Header");
85
86
// Convert to plain object
87
const plainHeaders = headers.toJSON();
88
console.log(plainHeaders);
89
```
90
91
### Static Methods
92
93
Factory and utility methods for header creation and manipulation.
94
95
```javascript { .api }
96
/**
97
* Create AxiosHeaders from various sources
98
* @param thing - Source to create headers from
99
* @returns New AxiosHeaders instance
100
*/
101
static AxiosHeaders.from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
102
103
/**
104
* Create header accessor for specific header
105
* @param header - Header name or names
106
* @returns AxiosHeaders with accessor methods
107
*/
108
static AxiosHeaders.accessor(header: string | string[]): AxiosHeaders;
109
110
/**
111
* Concatenate multiple header sources
112
* @param targets - Header sources to concatenate
113
* @returns New AxiosHeaders with combined headers
114
*/
115
static AxiosHeaders.concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
116
```
117
118
**Usage Examples:**
119
120
```javascript
121
// Create from different sources
122
const fromObject = AxiosHeaders.from({
123
"Content-Type": "application/json"
124
});
125
126
const fromString = AxiosHeaders.from("Content-Type: application/json\r\nAuthorization: Bearer token");
127
128
const fromExisting = AxiosHeaders.from(existingHeaders);
129
130
// Create accessor
131
const contentTypeAccessor = AxiosHeaders.accessor("Content-Type");
132
133
// Concatenate headers
134
const combined = AxiosHeaders.concat(
135
{ "Accept": "application/json" },
136
new AxiosHeaders({ "Authorization": "Bearer token" }),
137
"X-Custom: value"
138
);
139
```
140
141
### Specialized Header Methods
142
143
Type-safe methods for common HTTP headers with automatic parsing and validation.
144
145
```javascript { .api }
146
// Content-Type management
147
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
148
getContentType(parser?: RegExp): RegExpExecArray | null;
149
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
150
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
151
152
// Content-Length management
153
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
154
getContentLength(parser?: RegExp): RegExpExecArray | null;
155
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
156
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
157
158
// Accept header management
159
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
160
getAccept(parser?: RegExp): RegExpExecArray | null;
161
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
162
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
163
164
// User-Agent management
165
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
166
getUserAgent(parser?: RegExp): RegExpExecArray | null;
167
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
168
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
169
170
// Content-Encoding management
171
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
172
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
173
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
174
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
175
176
// Authorization management
177
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
178
getAuthorization(parser?: RegExp): RegExpExecArray | null;
179
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
180
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
181
182
// Set-Cookie handling
183
getSetCookie(): string[];
184
185
type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data'
186
| 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
187
```
188
189
**Usage Examples:**
190
191
```javascript
192
const headers = new AxiosHeaders();
193
194
// Content-Type management
195
headers.setContentType("application/json");
196
headers.setContentType("multipart/form-data", true); // Force rewrite
197
198
const contentType = headers.getContentType();
199
console.log(contentType); // "multipart/form-data"
200
201
if (headers.hasContentType(/^application\//)) {
202
console.log("Application content type");
203
}
204
205
// Authorization management
206
headers.setAuthorization("Bearer eyJhbGciOiJIUzI1NiIs...");
207
const authToken = headers.getAuthorization(/Bearer (.+)/);
208
console.log(authToken); // ["Bearer eyJhbGc...", "eyJhbGc..."]
209
210
// Accept header
211
headers.setAccept("application/json, text/plain, */*");
212
213
// User-Agent
214
headers.setUserAgent("MyApp/1.0 (Platform/Version)");
215
216
// Content-Length (usually set automatically)
217
headers.setContentLength(1024);
218
219
// Set-Cookie handling (typically in responses)
220
const cookies = headers.getSetCookie(); // Returns array of cookie strings
221
```
222
223
### Header Iteration
224
225
Iterate over headers using standard iteration methods.
226
227
```javascript { .api }
228
/**
229
* Iterator for header name-value pairs
230
*/
231
[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;
232
```
233
234
**Usage Examples:**
235
236
```javascript
237
const headers = new AxiosHeaders({
238
"Content-Type": "application/json",
239
"Authorization": "Bearer token",
240
"Accept": "application/json"
241
});
242
243
// Iterate over all headers
244
for (const [name, value] of headers) {
245
console.log(`${name}: ${value}`);
246
}
247
248
// Convert to array
249
const headerEntries = Array.from(headers);
250
251
// Use with destructuring
252
const headerMap = new Map(headers);
253
```
254
255
### Request and Response Header Types
256
257
Type definitions for request and response headers.
258
259
```javascript { .api }
260
// Request headers
261
interface RawAxiosRequestHeaders extends Partial<RawAxiosHeaders & {
262
'Accept': AxiosHeaderValue;
263
'Content-Length': AxiosHeaderValue;
264
'User-Agent': AxiosHeaderValue;
265
'Content-Encoding': AxiosHeaderValue;
266
'Authorization': AxiosHeaderValue;
267
'Content-Type': ContentType;
268
}> {}
269
270
type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
271
272
// Response headers
273
interface RawAxiosResponseHeaders extends Partial<RawAxiosHeaders & {
274
'Server': AxiosHeaderValue;
275
'Content-Type': AxiosHeaderValue;
276
'Content-Length': AxiosHeaderValue;
277
'Cache-Control': AxiosHeaderValue;
278
'Content-Encoding': AxiosHeaderValue;
279
'set-cookie': string[];
280
}> {}
281
282
type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
283
284
// Method-specific headers
285
type MethodsHeaders = Partial<{
286
[Key in Method as Lowercase<Key>]: AxiosHeaders;
287
} & {common: AxiosHeaders}>;
288
```
289
290
### Default Headers Configuration
291
292
Configure default headers for different HTTP methods.
293
294
```javascript { .api }
295
interface HeadersDefaults {
296
common: RawAxiosRequestHeaders;
297
delete: RawAxiosRequestHeaders;
298
get: RawAxiosRequestHeaders;
299
head: RawAxiosRequestHeaders;
300
post: RawAxiosRequestHeaders;
301
put: RawAxiosRequestHeaders;
302
patch: RawAxiosRequestHeaders;
303
options?: RawAxiosRequestHeaders;
304
purge?: RawAxiosRequestHeaders;
305
link?: RawAxiosRequestHeaders;
306
unlink?: RawAxiosRequestHeaders;
307
}
308
```
309
310
**Usage Examples:**
311
312
```javascript
313
import axios from "axios";
314
315
// Set common headers for all requests
316
axios.defaults.headers.common["Authorization"] = "Bearer token123";
317
axios.defaults.headers.common["X-API-Version"] = "v2";
318
319
// Set method-specific headers
320
axios.defaults.headers.post["Content-Type"] = "application/json";
321
axios.defaults.headers.get["Accept"] = "application/json";
322
323
// Instance-specific headers
324
const apiClient = axios.create();
325
apiClient.defaults.headers.common["User-Agent"] = "MyApp/1.0";
326
apiClient.defaults.headers.post["Content-Type"] = "application/json";
327
328
// Headers in request config
329
const response = await axios.get("/api/users", {
330
headers: {
331
"Accept": "application/json",
332
"X-Request-ID": generateRequestId()
333
}
334
});
335
336
// Using AxiosHeaders in config
337
const customHeaders = new AxiosHeaders()
338
.setAuthorization("Bearer token")
339
.setContentType("application/json")
340
.set("X-Custom", "value");
341
342
const postResponse = await axios.post("/api/data", payload, {
343
headers: customHeaders
344
});
345
```
346
347
### Header Matching and Filtering
348
349
Advanced header matching with custom matchers.
350
351
**Usage Examples:**
352
353
```javascript
354
const headers = new AxiosHeaders({
355
"Content-Type": "application/json",
356
"X-Custom-Header": "custom-value",
357
"Authorization": "Bearer token123",
358
"Accept": "application/json, text/plain"
359
});
360
361
// String matcher (case-insensitive)
362
const hasAuth = headers.has("authorization");
363
364
// RegExp matcher
365
const hasJsonContent = headers.has("Content-Type", /application\/json/);
366
367
// Function matcher
368
const hasCustomHeaders = headers.has("", (value, name) => {
369
return name.toLowerCase().startsWith("x-");
370
});
371
372
// Delete headers matching pattern
373
headers.delete("", /^x-/i); // Delete all X- headers
374
375
// Clear headers with custom matcher
376
headers.clear((value, name) => {
377
return name.toLowerCase().includes("temp");
378
});
379
380
// Conditional header setting
381
const rewriteIfEmpty = (value, name) => !value || value.length === 0;
382
headers.set("Accept", "application/json", rewriteIfEmpty);
383
```
384
385
### Advanced Header Patterns
386
387
Complex header management patterns for real-world applications.
388
389
**Usage Examples:**
390
391
```javascript
392
// Header builder pattern
393
class HeaderBuilder {
394
constructor() {
395
this.headers = new AxiosHeaders();
396
}
397
398
auth(token) {
399
this.headers.setAuthorization(`Bearer ${token}`);
400
return this;
401
}
402
403
json() {
404
this.headers.setContentType("application/json");
405
this.headers.setAccept("application/json");
406
return this;
407
}
408
409
userAgent(ua) {
410
this.headers.setUserAgent(ua);
411
return this;
412
}
413
414
custom(name, value) {
415
this.headers.set(name, value);
416
return this;
417
}
418
419
build() {
420
return this.headers;
421
}
422
}
423
424
// Usage
425
const headers = new HeaderBuilder()
426
.auth("token123")
427
.json()
428
.userAgent("MyApp/1.0")
429
.custom("X-Request-ID", generateId())
430
.build();
431
432
// Conditional headers
433
function buildHeaders(options = {}) {
434
const headers = new AxiosHeaders();
435
436
if (options.auth) {
437
headers.setAuthorization(`Bearer ${options.auth}`);
438
}
439
440
if (options.contentType) {
441
headers.setContentType(options.contentType);
442
} else {
443
headers.setContentType("application/json");
444
}
445
446
if (options.accept) {
447
headers.setAccept(options.accept);
448
}
449
450
if (options.custom) {
451
Object.entries(options.custom).forEach(([name, value]) => {
452
headers.set(name, value);
453
});
454
}
455
456
return headers;
457
}
458
459
// Header merging strategy
460
function mergeHeaders(base, override) {
461
const result = AxiosHeaders.from(base);
462
463
if (override) {
464
return result.concat(override);
465
}
466
467
return result;
468
}
469
470
// Dynamic headers based on environment
471
function getEnvironmentHeaders() {
472
const headers = new AxiosHeaders();
473
474
if (process.env.NODE_ENV === "development") {
475
headers.set("X-Debug", "true");
476
}
477
478
if (process.env.API_VERSION) {
479
headers.set("X-API-Version", process.env.API_VERSION);
480
}
481
482
return headers;
483
}
484
```