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

request-configuration.md docs/

1
# Request Configuration
2
3
Comprehensive configuration system for customizing all aspects of HTTP requests including URLs, headers, timeouts, authentication, data transformation, and more.
4
5
## Capabilities
6
7
### Request Configuration Interface
8
9
Complete configuration options for HTTP requests.
10
11
```typescript { .api }
12
interface AxiosRequestConfig<D = any> {
13
/** Request URL */
14
url?: string;
15
16
/** HTTP method */
17
method?: Method | string;
18
19
/** Base URL for relative URLs */
20
baseURL?: string;
21
22
/** Transform request data before sending */
23
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
24
25
/** Transform response data after receiving */
26
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
27
28
/** Request headers */
29
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
30
31
/** URL parameters */
32
params?: any;
33
34
/** Parameter serialization options */
35
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
36
37
/** Request body data */
38
data?: D;
39
40
/** Request timeout in milliseconds */
41
timeout?: number;
42
43
/** Custom timeout error message */
44
timeoutErrorMessage?: string;
45
46
/** Send credentials with cross-origin requests */
47
withCredentials?: boolean;
48
49
/** Request adapter configuration */
50
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
51
52
/** HTTP basic authentication */
53
auth?: AxiosBasicCredentials;
54
55
/** Response data type */
56
responseType?: ResponseType;
57
58
/** Response text encoding */
59
responseEncoding?: responseEncoding | string;
60
61
/** XSRF cookie name */
62
xsrfCookieName?: string;
63
64
/** XSRF header name */
65
xsrfHeaderName?: string;
66
67
/** Upload progress callback */
68
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
69
70
/** Download progress callback */
71
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
72
73
/** Maximum response content length */
74
maxContentLength?: number;
75
76
/** Status code validation function */
77
validateStatus?: ((status: number) => boolean) | null;
78
79
/** Maximum request body length */
80
maxBodyLength?: number;
81
82
/** Maximum redirects to follow */
83
maxRedirects?: number;
84
85
/** Upload/download rate limiting */
86
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
87
88
/** Before redirect callback */
89
beforeRedirect?: (options: Record<string, any>, responseDetails: { headers: Record<string, string> }) => void;
90
91
/** Unix socket path */
92
socketPath?: string | null;
93
94
/** Custom transport */
95
transport?: any;
96
97
/** HTTP agent for Node.js */
98
httpAgent?: any;
99
100
/** HTTPS agent for Node.js */
101
httpsAgent?: any;
102
103
/** Proxy configuration */
104
proxy?: AxiosProxyConfig | false;
105
106
/** Legacy cancellation token */
107
cancelToken?: CancelToken;
108
109
/** Decompress response */
110
decompress?: boolean;
111
112
/** Transitional options */
113
transitional?: TransitionalOptions;
114
115
/** Modern cancellation signal */
116
signal?: GenericAbortSignal;
117
118
/** Use insecure HTTP parser */
119
insecureHTTPParser?: boolean;
120
121
/** Environment configuration */
122
env?: {
123
FormData?: new (...args: any[]) => object;
124
};
125
126
/** Form serialization options */
127
formSerializer?: FormSerializerOptions;
128
129
/** IP address family */
130
family?: AddressFamily;
131
132
/** DNS lookup function */
133
lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
134
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
135
136
/** XSRF token handling */
137
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
138
}
139
140
type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK';
141
142
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream';
143
144
type AddressFamily = 4 | 6 | undefined;
145
```
146
147
**Usage Examples:**
148
149
```typescript
150
import axios from "axios";
151
152
// Complete configuration example
153
const config: AxiosRequestConfig = {
154
method: "post",
155
url: "https://api.example.com/users",
156
baseURL: "https://api.example.com",
157
headers: {
158
"Authorization": "Bearer token",
159
"Content-Type": "application/json",
160
"X-Custom-Header": "value"
161
},
162
data: {
163
name: "John Doe",
164
email: "john@example.com"
165
},
166
params: {
167
include: "profile,preferences"
168
},
169
timeout: 10000,
170
withCredentials: true,
171
responseType: "json",
172
validateStatus: (status) => status >= 200 && status < 300,
173
maxRedirects: 5,
174
onUploadProgress: (progressEvent) => {
175
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
176
console.log(`Upload ${percentCompleted}% completed`);
177
}
178
};
179
180
const response = await axios(config);
181
```
182
183
### Response Configuration
184
185
Structure of HTTP response objects returned by axios.
186
187
```typescript { .api }
188
interface AxiosResponse<T = any, D = any> {
189
/** Response data */
190
data: T;
191
192
/** HTTP status code */
193
status: number;
194
195
/** HTTP status text */
196
statusText: string;
197
198
/** Response headers */
199
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
200
201
/** Request configuration used */
202
config: InternalAxiosRequestConfig<D>;
203
204
/** Request object (platform-specific) */
205
request?: any;
206
}
207
208
type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
209
210
type RawCommonResponseHeaders = {
211
[Key in CommonResponseHeadersList]: AxiosHeaderValue;
212
} & {
213
"set-cookie": string[];
214
};
215
216
type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control' | 'Content-Encoding';
217
```
218
219
**Usage Examples:**
220
221
```typescript
222
import axios from "axios";
223
224
const response = await axios.get("https://api.example.com/users/123");
225
226
// Access response properties
227
console.log(response.data); // Response body
228
console.log(response.status); // 200
229
console.log(response.statusText); // "OK"
230
console.log(response.headers["content-type"]); // "application/json"
231
console.log(response.config.url); // Original request URL
232
233
// Typed response
234
interface User {
235
id: number;
236
name: string;
237
email: string;
238
}
239
240
const response = await axios.get<User>("https://api.example.com/users/123");
241
console.log(response.data.name); // TypeScript knows this is a string
242
```
243
244
### Authentication Configuration
245
246
HTTP authentication options including basic auth and bearer tokens.
247
248
```typescript { .api }
249
interface AxiosBasicCredentials {
250
username: string;
251
password: string;
252
}
253
```
254
255
**Usage Examples:**
256
257
```typescript
258
import axios from "axios";
259
260
// Basic authentication
261
const response = await axios.get("https://api.example.com/secure", {
262
auth: {
263
username: "myuser",
264
password: "mypassword"
265
}
266
});
267
268
// Bearer token in headers
269
const response = await axios.get("https://api.example.com/secure", {
270
headers: {
271
"Authorization": "Bearer your-jwt-token"
272
}
273
});
274
275
// API key authentication
276
const response = await axios.get("https://api.example.com/data", {
277
headers: {
278
"X-API-Key": "your-api-key"
279
}
280
});
281
282
// Custom authentication
283
const response = await axios.get("https://api.example.com/secure", {
284
headers: {
285
"Authorization": "Custom your-custom-token"
286
}
287
});
288
```
289
290
### Proxy Configuration
291
292
HTTP proxy settings for routing requests through proxy servers.
293
294
```typescript { .api }
295
interface AxiosProxyConfig {
296
host: string;
297
port: number;
298
auth?: AxiosBasicCredentials;
299
protocol?: string;
300
}
301
```
302
303
**Usage Examples:**
304
305
```typescript
306
import axios from "axios";
307
308
// HTTP proxy
309
const response = await axios.get("https://api.example.com/data", {
310
proxy: {
311
host: "proxy.company.com",
312
port: 8080
313
}
314
});
315
316
// Proxy with authentication
317
const response = await axios.get("https://api.example.com/data", {
318
proxy: {
319
host: "proxy.company.com",
320
port: 8080,
321
auth: {
322
username: "proxyuser",
323
password: "proxypass"
324
}
325
}
326
});
327
328
// HTTPS proxy
329
const response = await axios.get("https://api.example.com/data", {
330
proxy: {
331
protocol: "https",
332
host: "secure-proxy.company.com",
333
port: 8443
334
}
335
});
336
337
// Disable proxy
338
const response = await axios.get("https://api.example.com/data", {
339
proxy: false
340
});
341
```
342
343
### Progress Tracking
344
345
Monitor upload and download progress with callback functions.
346
347
```typescript { .api }
348
interface AxiosProgressEvent {
349
loaded: number;
350
total?: number;
351
progress?: number;
352
bytes: number;
353
rate?: number;
354
estimated?: number;
355
upload?: boolean;
356
download?: boolean;
357
event?: any;
358
}
359
```
360
361
**Usage Examples:**
362
363
```typescript
364
import axios from "axios";
365
366
// Upload progress
367
const formData = new FormData();
368
formData.append("file", fileInput.files[0]);
369
370
const response = await axios.post("https://api.example.com/upload", formData, {
371
onUploadProgress: (progressEvent) => {
372
if (progressEvent.total) {
373
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
374
console.log(`Upload ${percentCompleted}% completed`);
375
376
// Update progress bar
377
updateProgressBar(percentCompleted);
378
}
379
380
// Show upload rate
381
if (progressEvent.rate) {
382
console.log(`Upload rate: ${(progressEvent.rate / 1024).toFixed(2)} KB/s`);
383
}
384
}
385
});
386
387
// Download progress
388
const response = await axios.get("https://api.example.com/download/largefile", {
389
responseType: "blob",
390
onDownloadProgress: (progressEvent) => {
391
if (progressEvent.total) {
392
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
393
console.log(`Download ${percentCompleted}% completed`);
394
395
// Estimated time remaining
396
if (progressEvent.estimated) {
397
console.log(`ETA: ${progressEvent.estimated}s`);
398
}
399
}
400
}
401
});
402
```
403
404
### Data Transformation
405
406
Transform request and response data automatically.
407
408
```typescript { .api }
409
interface AxiosRequestTransformer {
410
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
411
}
412
413
interface AxiosResponseTransformer {
414
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
415
}
416
```
417
418
**Usage Examples:**
419
420
```typescript
421
import axios from "axios";
422
423
// Custom request transformer
424
const api = axios.create({
425
transformRequest: [
426
function (data, headers) {
427
// Transform request data
428
if (data && typeof data === "object") {
429
// Convert dates to ISO strings
430
const transformed = { ...data };
431
Object.keys(transformed).forEach(key => {
432
if (transformed[key] instanceof Date) {
433
transformed[key] = transformed[key].toISOString();
434
}
435
});
436
return JSON.stringify(transformed);
437
}
438
return data;
439
},
440
...axios.defaults.transformRequest // Include default transformers
441
]
442
});
443
444
// Custom response transformer
445
const api = axios.create({
446
transformResponse: [
447
...axios.defaults.transformResponse, // Include default transformers
448
function (data) {
449
// Parse date strings back to Date objects
450
if (data && typeof data === "object") {
451
Object.keys(data).forEach(key => {
452
if (typeof data[key] === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(data[key])) {
453
data[key] = new Date(data[key]);
454
}
455
});
456
}
457
return data;
458
}
459
]
460
});
461
462
// Use transformed data
463
const user = await api.post("/users", {
464
name: "John",
465
birthDate: new Date("1990-01-01") // Automatically converted to ISO string
466
});
467
468
console.log(user.data.birthDate instanceof Date); // true - converted back to Date
469
```
470
471
### Timeout and Validation
472
473
Request timeout and response validation configuration.
474
475
**Usage Examples:**
476
477
```typescript
478
import axios from "axios";
479
480
// Timeout configuration
481
const response = await axios.get("https://api.example.com/data", {
482
timeout: 5000, // 5 seconds
483
timeoutErrorMessage: "Request took too long to complete"
484
});
485
486
// Custom status validation
487
const response = await axios.get("https://api.example.com/data", {
488
validateStatus: function (status) {
489
// Accept 2xx and 3xx as successful
490
return status >= 200 && status < 400;
491
}
492
});
493
494
// Accept specific error codes as successful
495
const response = await axios.get("https://api.example.com/optional-data", {
496
validateStatus: function (status) {
497
// Accept 200 (OK) and 404 (Not Found) as successful
498
return status === 200 || status === 404;
499
}
500
});
501
502
if (response.status === 404) {
503
console.log("Data not found, using defaults");
504
} else {
505
console.log("Data retrieved:", response.data);
506
}
507
```