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@0.30.0

configuration.md docs/

1
# Configuration
2
3
Comprehensive configuration system providing hierarchical configuration merging from global defaults, instance defaults, and request-specific overrides. Supports extensive customization of request behavior, timeouts, authentication, data transformation, and more.
4
5
## Capabilities
6
7
### Default Configuration Access
8
9
Access and modify the global default configuration that applies to all requests.
10
11
```javascript { .api }
12
/**
13
* Global default configuration object
14
*/
15
axios.defaults: AxiosDefaults;
16
```
17
18
**Usage Examples:**
19
20
```javascript
21
// Set global base URL
22
axios.defaults.baseURL = 'https://api.example.com';
23
24
// Set global timeout
25
axios.defaults.timeout = 10000;
26
27
// Set global headers
28
axios.defaults.headers.common['Authorization'] = 'Bearer token123';
29
axios.defaults.headers.post['Content-Type'] = 'application/json';
30
31
// View current defaults
32
console.log(axios.defaults.timeout); // 10000
33
console.log(axios.defaults.baseURL); // https://api.example.com
34
```
35
36
### Request Configuration Options
37
38
Complete configuration interface for customizing individual requests.
39
40
```javascript { .api }
41
interface AxiosRequestConfig<D = any> {
42
/** Request URL */
43
url?: string;
44
/** HTTP method (defaults to 'get') */
45
method?: Method | string;
46
/** Base URL prepended to url unless url is absolute */
47
baseURL?: string;
48
/** Allow absolute URLs when using baseURL */
49
allowAbsoluteUrls?: boolean;
50
/** Functions to transform request data */
51
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
52
/** Functions to transform response data */
53
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
54
/** Request headers */
55
headers?: AxiosRequestHeaders;
56
/** URL parameters object */
57
params?: any;
58
/** URL parameters serializer configuration */
59
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
60
/** Request body data */
61
data?: D;
62
/** Request timeout in milliseconds (0 = no timeout) */
63
timeout?: number;
64
/** Timeout error message */
65
timeoutErrorMessage?: string;
66
/** Send cookies with cross-origin requests */
67
withCredentials?: boolean;
68
/** Custom adapter for handling requests */
69
adapter?: AxiosAdapter;
70
/** Basic authentication credentials */
71
auth?: AxiosBasicCredentials;
72
/** Response data type */
73
responseType?: ResponseType;
74
/** Response encoding (Node.js only) */
75
responseEncoding?: responseEncoding | string;
76
/** XSRF cookie name */
77
xsrfCookieName?: string;
78
/** XSRF header name */
79
xsrfHeaderName?: string;
80
/** Upload progress callback */
81
onUploadProgress?: (progressEvent: ProgressEvent) => void;
82
/** Download progress callback */
83
onDownloadProgress?: (progressEvent: ProgressEvent) => void;
84
/** Max request content length in bytes */
85
maxContentLength?: number;
86
/** Status code validation function */
87
validateStatus?: ((status: number) => boolean) | null;
88
/** Max request body length in bytes */
89
maxBodyLength?: number;
90
/** Max redirects to follow */
91
maxRedirects?: number;
92
/** Hook called before redirect */
93
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
94
/** Unix socket path (Node.js only) */
95
socketPath?: string | null;
96
/** HTTP agent (Node.js only) */
97
httpAgent?: any;
98
/** HTTPS agent (Node.js only) */
99
httpsAgent?: any;
100
/** Proxy configuration */
101
proxy?: AxiosProxyConfig | false;
102
/** Cancellation token (legacy) */
103
cancelToken?: CancelToken;
104
/** Decompress response body */
105
decompress?: boolean;
106
/** Transitional behavior options */
107
transitional?: TransitionalOptions;
108
/** AbortController signal (modern cancellation) */
109
signal?: GenericAbortSignal;
110
/** Insecure HTTP parser */
111
insecureHTTPParser?: boolean;
112
/** Environment-specific classes */
113
env?: {
114
FormData?: new (...args: any[]) => object;
115
};
116
/** Form data serialization options */
117
formSerializer?: FormSerializerOptions;
118
/** XSRF token function or boolean */
119
withXSRFToken?: boolean | ((config: AxiosRequestConfig) => boolean | undefined);
120
}
121
```
122
123
**Usage Examples:**
124
125
```javascript
126
// Comprehensive request configuration
127
const response = await axios({
128
method: 'post',
129
url: '/users',
130
baseURL: 'https://api.example.com',
131
timeout: 5000,
132
headers: {
133
'Content-Type': 'application/json',
134
'Authorization': 'Bearer token123'
135
},
136
params: { include: 'profile' },
137
data: { name: 'John', email: 'john@example.com' },
138
validateStatus: (status) => status < 500,
139
onUploadProgress: (event) => {
140
console.log(`Upload progress: ${(event.loaded / event.total) * 100}%`);
141
}
142
});
143
```
144
145
### HTTP Methods
146
147
Supported HTTP methods for the method configuration option.
148
149
```javascript { .api }
150
type Method =
151
| 'get' | 'GET'
152
| 'delete' | 'DELETE'
153
| 'head' | 'HEAD'
154
| 'options' | 'OPTIONS'
155
| 'post' | 'POST'
156
| 'put' | 'PUT'
157
| 'patch' | 'PATCH'
158
| 'purge' | 'PURGE'
159
| 'link' | 'LINK'
160
| 'unlink' | 'UNLINK';
161
```
162
163
### Response Types
164
165
Available response data types for the responseType configuration option.
166
167
```javascript { .api }
168
type ResponseType =
169
| 'arraybuffer' // ArrayBuffer object
170
| 'blob' // Blob object (browser only)
171
| 'document' // DOM Document (browser only)
172
| 'json' // JSON object (default)
173
| 'text' // String
174
| 'stream'; // Node.js readable stream
175
```
176
177
**Usage Examples:**
178
179
```javascript
180
// Download binary data
181
const response = await axios.get('/files/image.png', {
182
responseType: 'arraybuffer'
183
});
184
const imageData = response.data; // ArrayBuffer
185
186
// Download as blob for file saving
187
const response = await axios.get('/files/document.pdf', {
188
responseType: 'blob'
189
});
190
const blob = response.data; // Blob object
191
192
// Stream large file (Node.js)
193
const response = await axios.get('/files/large-file.zip', {
194
responseType: 'stream'
195
});
196
response.data.pipe(fs.createWriteStream('output.zip'));
197
```
198
199
### Authentication Configuration
200
201
Built-in support for HTTP Basic authentication.
202
203
```javascript { .api }
204
interface AxiosBasicCredentials {
205
username: string;
206
password: string;
207
}
208
```
209
210
**Usage Examples:**
211
212
```javascript
213
// Basic authentication
214
const response = await axios.get('/protected', {
215
auth: {
216
username: 'john',
217
password: 'secret123'
218
}
219
});
220
221
// Equivalent to setting Authorization header
222
const response = await axios.get('/protected', {
223
headers: {
224
'Authorization': 'Basic ' + btoa('john:secret123')
225
}
226
});
227
```
228
229
### Proxy Configuration
230
231
HTTP/HTTPS proxy support for Node.js environments.
232
233
```javascript { .api }
234
interface AxiosProxyConfig {
235
host: string;
236
port: number;
237
auth?: {
238
username: string;
239
password: string;
240
};
241
protocol?: string;
242
}
243
```
244
245
**Usage Examples:**
246
247
```javascript
248
// HTTP proxy
249
const response = await axios.get('https://api.example.com/data', {
250
proxy: {
251
host: '127.0.0.1',
252
port: 8080
253
}
254
});
255
256
// Authenticated proxy
257
const response = await axios.get('https://api.example.com/data', {
258
proxy: {
259
host: 'proxy.company.com',
260
port: 3128,
261
auth: {
262
username: 'proxyuser',
263
password: 'proxypass'
264
},
265
protocol: 'http'
266
}
267
});
268
269
// Disable proxy
270
const response = await axios.get('https://api.example.com/data', {
271
proxy: false
272
});
273
```
274
275
### Data Transformation
276
277
Configure how request and response data is processed.
278
279
```javascript { .api }
280
interface AxiosRequestTransformer {
281
(data: any, headers: AxiosRequestHeaders): any;
282
}
283
284
interface AxiosResponseTransformer {
285
(data: any, headers?: AxiosResponseHeaders, status?: number): any;
286
}
287
```
288
289
**Usage Examples:**
290
291
```javascript
292
// Custom request transformer
293
axios.defaults.transformRequest = [
294
(data, headers) => {
295
// Transform data before sending
296
if (data && typeof data === 'object') {
297
// Add timestamp to all requests
298
data._timestamp = Date.now();
299
}
300
return JSON.stringify(data);
301
}
302
];
303
304
// Custom response transformer
305
axios.defaults.transformResponse = [
306
(data) => {
307
// Parse and transform response
308
const parsed = JSON.parse(data);
309
310
// Unwrap data from API wrapper
311
if (parsed && parsed.result) {
312
return parsed.result;
313
}
314
315
return parsed;
316
}
317
];
318
319
// Request-specific transformers
320
const response = await axios.post('/data', requestData, {
321
transformRequest: [
322
(data, headers) => {
323
// Custom transformation for this request
324
return btoa(JSON.stringify(data)); // Base64 encode
325
}
326
],
327
transformResponse: [
328
(data) => {
329
// Custom response parsing
330
return JSON.parse(atob(data)); // Base64 decode
331
}
332
]
333
});
334
```
335
336
### Headers Configuration
337
338
Flexible header management with method-specific defaults.
339
340
```javascript { .api }
341
interface HeadersDefaults {
342
common: AxiosRequestHeaders; // Headers for all methods
343
delete: AxiosRequestHeaders; // Headers for DELETE requests
344
get: AxiosRequestHeaders; // Headers for GET requests
345
head: AxiosRequestHeaders; // Headers for HEAD requests
346
post: AxiosRequestHeaders; // Headers for POST requests
347
put: AxiosRequestHeaders; // Headers for PUT requests
348
patch: AxiosRequestHeaders; // Headers for PATCH requests
349
options?: AxiosRequestHeaders; // Headers for OPTIONS requests
350
purge?: AxiosRequestHeaders; // Headers for PURGE requests
351
link?: AxiosRequestHeaders; // Headers for LINK requests
352
unlink?: AxiosRequestHeaders; // Headers for UNLINK requests
353
}
354
```
355
356
**Usage Examples:**
357
358
```javascript
359
// Set headers for all requests
360
axios.defaults.headers.common['Authorization'] = 'Bearer token123';
361
axios.defaults.headers.common['User-Agent'] = 'MyApp/1.0';
362
363
// Set headers for specific methods
364
axios.defaults.headers.post['Content-Type'] = 'application/json';
365
axios.defaults.headers.get['Accept'] = 'application/json';
366
367
// Instance-specific headers
368
const apiClient = axios.create({
369
baseURL: 'https://api.example.com',
370
headers: {
371
common: {
372
'Authorization': 'Bearer instance-token'
373
},
374
post: {
375
'Content-Type': 'application/json'
376
}
377
}
378
});
379
380
// Request-specific headers (highest priority)
381
const response = await axios.get('/data', {
382
headers: {
383
'Accept': 'application/xml', // Overrides default
384
'X-Custom': 'value' // Additional header
385
}
386
});
387
```
388
389
### Timeout Configuration
390
391
Configure request timeouts and error messages.
392
393
```javascript { .api }
394
interface TimeoutConfig {
395
/** Timeout in milliseconds (0 = no timeout) */
396
timeout?: number;
397
/** Custom timeout error message */
398
timeoutErrorMessage?: string;
399
}
400
```
401
402
**Usage Examples:**
403
404
```javascript
405
// Global timeout
406
axios.defaults.timeout = 10000; // 10 seconds
407
408
// Request-specific timeout
409
const response = await axios.get('/slow-endpoint', {
410
timeout: 30000, // 30 seconds for this request
411
timeoutErrorMessage: 'The request took too long to complete'
412
});
413
414
// No timeout for specific request
415
const response = await axios.get('/streaming-data', {
416
timeout: 0 // No timeout
417
});
418
```
419
420
### URL Parameter Serialization
421
422
Configure how URL parameters are serialized.
423
424
```javascript { .api }
425
interface ParamsSerializerOptions extends SerializerOptions {
426
encode?: ParamEncoder;
427
serialize?: CustomParamsSerializer;
428
}
429
430
interface ParamEncoder {
431
(value: any, defaultEncoder: (value: any) => any): any;
432
}
433
434
interface CustomParamsSerializer {
435
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
436
}
437
```
438
439
**Usage Examples:**
440
441
```javascript
442
// Custom parameter encoding
443
const response = await axios.get('/search', {
444
params: {
445
q: 'hello world',
446
tags: ['javascript', 'api'],
447
nested: { key: 'value' }
448
},
449
paramsSerializer: {
450
encode: (value, defaultEncoder) => {
451
// Custom encoding logic
452
return encodeURIComponent(value);
453
},
454
serialize: (params) => {
455
// Custom serialization
456
return Object.keys(params)
457
.map(key => `${key}=${params[key]}`)
458
.join('&');
459
}
460
}
461
});
462
463
// Array parameter handling
464
const response = await axios.get('/items', {
465
params: {
466
ids: [1, 2, 3],
467
categories: ['tech', 'news']
468
},
469
paramsSerializer: {
470
indexes: false, // ids=1&ids=2&ids=3 instead of ids[0]=1&ids[1]=2&ids[2]=3
471
}
472
});
473
```
474
475
### Transitional Options
476
477
Backward compatibility and transitional behavior configuration.
478
479
```javascript { .api }
480
interface TransitionalOptions {
481
/** Silently parse JSON responses even if not JSON content type */
482
silentJSONParsing?: boolean;
483
/** Force JSON parsing for all responses */
484
forcedJSONParsing?: boolean;
485
/** Provide more descriptive timeout error messages */
486
clarifyTimeoutError?: boolean;
487
}
488
```
489
490
**Usage Examples:**
491
492
```javascript
493
// Configure transitional behavior
494
axios.defaults.transitional = {
495
silentJSONParsing: true, // Don't throw on JSON parse errors
496
forcedJSONParsing: false, // Only parse JSON for JSON content types
497
clarifyTimeoutError: true // Better timeout error messages
498
};
499
500
// Request-specific transitional options
501
const response = await axios.get('/legacy-api', {
502
transitional: {
503
silentJSONParsing: false, // Strict JSON parsing for this request
504
forcedJSONParsing: true // Force JSON parsing regardless of content type
505
}
506
});
507
```
508
509
### Status Code Validation
510
511
Customize which HTTP status codes are considered successful.
512
513
```javascript { .api }
514
/**
515
* Function to validate HTTP status codes
516
* @param status - HTTP status code
517
* @returns true if status should resolve promise, false if it should reject
518
*/
519
validateStatus?: ((status: number) => boolean) | null;
520
```
521
522
**Usage Examples:**
523
524
```javascript
525
// Default validation (200-299 are successful)
526
axios.defaults.validateStatus = (status) => status >= 200 && status < 300;
527
528
// Accept 404 as successful for existence checks
529
const response = await axios.get('/users/123', {
530
validateStatus: (status) => status === 200 || status === 404
531
});
532
533
if (response.status === 404) {
534
console.log('User not found');
535
} else {
536
console.log('User found:', response.data);
537
}
538
539
// Treat all responses as successful (handle errors manually)
540
const response = await axios.get('/api/data', {
541
validateStatus: () => true
542
});
543
544
if (response.status >= 400) {
545
console.log('Error response:', response.status);
546
} else {
547
console.log('Success:', response.data);
548
}
549
```