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

index.md docs/

1
# Axios
2
3
Axios is a Promise-based HTTP client for the browser and Node.js. It provides a simple and consistent API for making HTTP requests with support for request and response interception, automatic request and response body transformation, cancellation, timeouts, and extensive configuration options.
4
5
## Package Information
6
7
- **Package Name**: axios
8
- **Package Type**: npm
9
- **Language**: JavaScript/TypeScript
10
- **Installation**: `npm install axios`
11
12
## Core Imports
13
14
```javascript
15
import axios from "axios";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const axios = require("axios");
22
```
23
24
Named imports:
25
26
```javascript
27
import { Axios, AxiosError, CancelToken, AxiosHeaders } from "axios";
28
```
29
30
## Basic Usage
31
32
```javascript
33
import axios from "axios";
34
35
// Simple GET request
36
const response = await axios.get("https://api.example.com/users");
37
console.log(response.data);
38
39
// POST request with data
40
const newUser = await axios.post("https://api.example.com/users", {
41
name: "John Doe",
42
email: "john@example.com"
43
});
44
45
// Request with custom configuration
46
const config = {
47
method: "get",
48
url: "https://api.example.com/data",
49
timeout: 5000,
50
headers: {
51
"Authorization": "Bearer token123"
52
}
53
};
54
55
const result = await axios(config);
56
```
57
58
## Architecture
59
60
Axios is built around several key components:
61
62
- **Default Instance**: Pre-configured instance accessible via the main export
63
- **Custom Instances**: User-created instances with custom defaults via `axios.create()`
64
- **Axios Class**: Core class providing HTTP methods and configuration management
65
- **Interceptor System**: Request/response interceptors for preprocessing and error handling
66
- **Adapter System**: Environment-specific request adapters (xhr, http, fetch)
67
- **Cancellation System**: Token-based request cancellation with CancelToken
68
- **Configuration Merging**: Hierarchical config merging from defaults, instance, and request level
69
- **Error Handling**: Structured error objects with detailed context and error codes
70
71
## Capabilities
72
73
### HTTP Client Instance
74
75
Core HTTP client functionality providing all standard HTTP methods with Promise-based responses. The main axios export is a pre-configured instance ready for immediate use.
76
77
```javascript { .api }
78
// Default axios instance - function interface
79
axios(config: AxiosRequestConfig): Promise<AxiosResponse>;
80
axios(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
81
82
// HTTP method shortcuts
83
axios.get(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
84
axios.post(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
85
axios.put(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
86
axios.patch(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
87
axios.delete(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
88
axios.head(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
89
axios.options(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
90
91
// Form-based methods
92
axios.postForm(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
93
axios.putForm(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
94
axios.patchForm(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
95
```
96
97
[HTTP Client](./http-client.md)
98
99
### Instance Creation and Configuration
100
101
Create custom axios instances with their own configuration defaults, useful for different APIs or environments.
102
103
```javascript { .api }
104
axios.create(config?: CreateAxiosDefaults): AxiosInstance;
105
106
interface CreateAxiosDefaults {
107
baseURL?: string;
108
timeout?: number;
109
headers?: RawAxiosRequestHeaders | AxiosHeaders;
110
// ... other AxiosRequestConfig properties
111
}
112
```
113
114
[Instance Management](./instance-management.md)
115
116
### Request and Response Interception
117
118
Intercept requests and responses to transform data, add authentication, handle errors, or implement retry logic.
119
120
```javascript { .api }
121
// Available on any axios instance
122
axios.interceptors.request.use(
123
onFulfilled?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>,
124
onRejected?: (error: any) => any,
125
options?: AxiosInterceptorOptions
126
): number;
127
128
axios.interceptors.response.use(
129
onFulfilled?: (response: AxiosResponse) => AxiosResponse | Promise<AxiosResponse>,
130
onRejected?: (error: any) => any
131
): number;
132
133
interface AxiosInterceptorOptions {
134
synchronous?: boolean;
135
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
136
}
137
```
138
139
[Interceptors](./interceptors.md)
140
141
### Request Cancellation
142
143
Cancel HTTP requests using tokens or AbortSignal to prevent unnecessary network usage and handle component cleanup.
144
145
```javascript { .api }
146
// CancelToken-based cancellation
147
const CancelToken = axios.CancelToken;
148
const source = CancelToken.source();
149
150
axios.get(url, { cancelToken: source.token });
151
source.cancel("Operation canceled");
152
153
// AbortSignal-based cancellation (modern approach)
154
const controller = new AbortController();
155
axios.get(url, { signal: controller.signal });
156
controller.abort();
157
```
158
159
[Request Cancellation](./cancellation.md)
160
161
### Error Handling
162
163
Structured error handling with detailed error information, error codes, and type checking utilities.
164
165
```javascript { .api }
166
// Error checking
167
axios.isAxiosError(error: any): boolean;
168
axios.isCancel(error: any): boolean;
169
170
// Error classes
171
class AxiosError extends Error {
172
config?: InternalAxiosRequestConfig;
173
code?: string;
174
request?: any;
175
response?: AxiosResponse;
176
isAxiosError: boolean;
177
status?: number;
178
}
179
180
class CanceledError extends AxiosError {}
181
```
182
183
[Error Handling](./error-handling.md)
184
185
### Headers Management
186
187
Advanced header manipulation with type-safe operations and automatic content-type handling.
188
189
```javascript { .api }
190
class AxiosHeaders {
191
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
192
193
set(headerName: string, value: AxiosHeaderValue, rewrite?: boolean): AxiosHeaders;
194
get(headerName: string, parser?: RegExp): RegExpExecArray | null;
195
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
196
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
197
198
// Specialized methods
199
setContentType(value: ContentType, rewrite?: boolean): AxiosHeaders;
200
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean): AxiosHeaders;
201
}
202
```
203
204
[Headers Management](./headers.md)
205
206
### Data Transformation and Serialization
207
208
Convert between different data formats including FormData, JSON, and URL-encoded data with extensive serialization options.
209
210
```javascript { .api }
211
// Form data conversion
212
axios.toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
213
axios.formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
214
215
// Configuration merging
216
axios.mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig;
217
218
// Adapter selection
219
axios.getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[]): AxiosAdapter;
220
```
221
222
[Data Transformation](./data-transformation.md)
223
224
### Utility Functions
225
226
Helper functions for common operations and compatibility with Promise patterns.
227
228
```javascript { .api }
229
/**
230
* Spread array of responses into separate arguments (Promise.all helper)
231
* @param callback - Function to call with spread arguments
232
* @returns Function that takes array and spreads it to callback
233
*/
234
axios.spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
235
236
/**
237
* Execute multiple requests concurrently (wrapper for Promise.all)
238
* @param promises - Array of axios request promises
239
* @returns Promise resolving to array of responses
240
*/
241
axios.all<T>(promises: Array<T | Promise<T>>): Promise<T[]>;
242
```
243
244
**Usage Examples:**
245
246
```javascript
247
import axios from "axios";
248
249
// Using spread to handle multiple concurrent requests
250
function getUserData(userIds) {
251
const requests = userIds.map(id => axios.get(`/users/${id}`));
252
253
return axios.all(requests)
254
.then(axios.spread((user1, user2, user3) => {
255
// Each parameter is a response object
256
console.log("User 1:", user1.data);
257
console.log("User 2:", user2.data);
258
console.log("User 3:", user3.data);
259
return [user1.data, user2.data, user3.data];
260
}));
261
}
262
263
// Modern async/await alternative
264
async function getUserDataModern(userIds) {
265
const requests = userIds.map(id => axios.get(`/users/${id}`));
266
const responses = await axios.all(requests);
267
return responses.map(response => response.data);
268
}
269
```
270
271
### Version Information
272
273
Access to the current axios library version.
274
275
```javascript { .api }
276
/**
277
* Current axios library version string
278
*/
279
axios.VERSION: string;
280
```
281
282
**Usage Examples:**
283
284
```javascript
285
console.log("Using axios version:", axios.VERSION); // "1.11.0"
286
287
// Useful for debugging or feature detection
288
if (axios.VERSION >= "1.0.0") {
289
// Use modern axios features
290
}
291
```
292
293
### HTTP Status Codes
294
295
Comprehensive enum of HTTP status codes with both numeric and named access.
296
297
```javascript { .api }
298
enum HttpStatusCode {
299
// 1xx Informational
300
Continue = 100,
301
SwitchingProtocols = 101,
302
Processing = 102,
303
EarlyHints = 103,
304
305
// 2xx Success
306
Ok = 200,
307
Created = 201,
308
Accepted = 202,
309
NoContent = 204,
310
PartialContent = 206,
311
312
// 3xx Redirection
313
MultipleChoices = 300,
314
MovedPermanently = 301,
315
Found = 302,
316
SeeOther = 303,
317
NotModified = 304,
318
TemporaryRedirect = 307,
319
PermanentRedirect = 308,
320
321
// 4xx Client Error
322
BadRequest = 400,
323
Unauthorized = 401,
324
Forbidden = 403,
325
NotFound = 404,
326
MethodNotAllowed = 405,
327
RequestTimeout = 408,
328
Conflict = 409,
329
Gone = 410,
330
PreconditionFailed = 412,
331
PayloadTooLarge = 413,
332
UnsupportedMediaType = 415,
333
ImATeapot = 418,
334
UnprocessableEntity = 422,
335
TooManyRequests = 429,
336
337
// 5xx Server Error
338
InternalServerError = 500,
339
NotImplemented = 501,
340
BadGateway = 502,
341
ServiceUnavailable = 503,
342
GatewayTimeout = 504
343
// ... includes all standard HTTP status codes
344
}
345
```
346
347
**Usage Examples:**
348
349
```javascript
350
import axios, { HttpStatusCode } from "axios";
351
352
try {
353
const response = await axios.get("/api/data");
354
355
if (response.status === HttpStatusCode.Ok) {
356
console.log("Success:", response.data);
357
}
358
} catch (error) {
359
if (error.response?.status === HttpStatusCode.NotFound) {
360
console.log("Resource not found");
361
} else if (error.response?.status === HttpStatusCode.Unauthorized) {
362
console.log("Authentication required");
363
} else if (error.response?.status >= HttpStatusCode.InternalServerError) {
364
console.log("Server error occurred");
365
}
366
}
367
368
// Use in status validation
369
const api = axios.create({
370
validateStatus: (status) => status < HttpStatusCode.InternalServerError
371
});
372
```
373
374
## Types
375
376
```javascript { .api }
377
interface AxiosRequestConfig<D = any> {
378
// Core request settings
379
url?: string;
380
method?: Method;
381
baseURL?: string;
382
data?: D;
383
params?: any;
384
385
// Headers and authentication
386
headers?: RawAxiosRequestHeaders | AxiosHeaders;
387
auth?: AxiosBasicCredentials;
388
withCredentials?: boolean;
389
390
// Data transformation
391
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
392
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
393
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
394
395
// Response handling
396
responseType?: ResponseType;
397
responseEncoding?: responseEncoding;
398
timeout?: number;
399
timeoutErrorMessage?: string;
400
validateStatus?: (status: number) => boolean;
401
402
// Progress tracking
403
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
404
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
405
406
// Request/Response size limits
407
maxContentLength?: number;
408
maxBodyLength?: number;
409
maxRedirects?: number;
410
maxRate?: number;
411
412
// Networking
413
proxy?: AxiosProxyConfig | false;
414
httpAgent?: any;
415
httpsAgent?: any;
416
socketPath?: string | null;
417
418
// Security
419
xsrfCookieName?: string;
420
xsrfHeaderName?: string;
421
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | Promise<boolean>);
422
423
// Cancellation
424
cancelToken?: CancelToken;
425
signal?: GenericAbortSignal;
426
427
// Advanced options
428
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
429
decompress?: boolean;
430
transitional?: TransitionalOptions;
431
insecureHTTPParser?: boolean;
432
env?: { FormData?: new (...args: any[]) => object };
433
formSerializer?: FormSerializerOptions;
434
435
// Node.js specific
436
lookup?: LookupAddress | LookupAddressEntry[];
437
family?: AddressFamily | undefined;
438
439
// Browser specific
440
fetchOptions?: Record<string, any>;
441
}
442
443
interface AxiosResponse<T = any> {
444
data: T;
445
status: number;
446
statusText: string;
447
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
448
config: InternalAxiosRequestConfig;
449
request?: any;
450
}
451
452
type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS'
453
| 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH';
454
455
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' | 'formdata';
456
457
interface AxiosProgressEvent {
458
loaded: number;
459
total?: number;
460
progress?: number;
461
bytes: number;
462
rate?: number;
463
estimated?: number;
464
upload?: boolean;
465
download?: boolean;
466
event?: BrowserProgressEvent;
467
lengthComputable: boolean;
468
}
469
470
interface TransitionalOptions {
471
silentJSONParsing?: boolean;
472
forcedJSONParsing?: boolean;
473
clarifyTimeoutError?: boolean;
474
}
475
476
interface AxiosBasicCredentials {
477
username: string;
478
password: string;
479
}
480
481
interface AxiosProxyConfig {
482
host: string;
483
port: number;
484
auth?: AxiosBasicCredentials;
485
protocol?: string;
486
}
487
488
interface ParamsSerializerOptions {
489
dots?: boolean;
490
indexes?: boolean | null;
491
encode?: (value: any, defaultEncoder: (value: any) => any) => any;
492
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions) => string;
493
}
494
```