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

index.md docs/

1
# Axios
2
3
Axios is a comprehensive promise-based HTTP client library designed for both browser and Node.js environments. It provides a clean, intuitive API for making HTTP requests with support for request and response interceptors, automatic JSON data transformation, client-side protection against XSRF, request and response timeout configuration, and comprehensive error handling.
4
5
## Package Information
6
7
- **Package Name**: axios
8
- **Package Type**: npm
9
- **Language**: JavaScript with TypeScript definitions
10
- **Installation**: `npm install axios`
11
12
## Core Imports
13
14
```typescript
15
import axios from "axios";
16
import { Axios, AxiosError, AxiosHeaders } from "axios";
17
```
18
19
For CommonJS:
20
21
```javascript
22
const axios = require("axios");
23
const { Axios, AxiosError, AxiosHeaders } = require("axios");
24
```
25
26
## Basic Usage
27
28
```typescript
29
import axios from "axios";
30
31
// Simple GET request
32
const response = await axios.get("https://api.example.com/users");
33
console.log(response.data);
34
35
// POST request with data
36
const newUser = await axios.post("https://api.example.com/users", {
37
name: "John Doe",
38
email: "john@example.com"
39
});
40
41
// Request with configuration
42
const config = {
43
method: "get",
44
url: "https://api.example.com/users",
45
headers: {
46
"Authorization": "Bearer token"
47
},
48
timeout: 5000
49
};
50
const response = await axios(config);
51
```
52
53
## Architecture
54
55
Axios is built around several key components:
56
57
- **Main Instance**: Default configured axios instance with HTTP method shortcuts
58
- **Axios Class**: Core HTTP client class for creating custom instances
59
- **Interceptors**: Request/response middleware for automatic processing
60
- **Adapters**: Platform-specific implementations (XMLHttpRequest for browser, HTTP for Node.js)
61
- **Error Handling**: Comprehensive error system with detailed error information
62
- **Configuration**: Extensive configuration options for all aspects of HTTP requests
63
- **Headers Management**: Sophisticated header handling with the AxiosHeaders class
64
- **Cancellation**: Request cancellation support via AbortController and legacy CancelToken
65
66
## Capabilities
67
68
### HTTP Methods
69
70
Core HTTP request methods with both functional and instance-based APIs. Supports all standard HTTP verbs with convenient method signatures.
71
72
```typescript { .api }
73
// Default instance methods
74
function get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
75
function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
76
function put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
77
function patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
78
function delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
79
function head<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
80
function options<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
81
82
// Generic request method
83
function request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>>;
84
85
// Form-encoded requests
86
function postForm<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
87
function putForm<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
88
function patchForm<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
89
```
90
91
[HTTP Methods](./http-methods.md)
92
93
### Instance Management
94
95
Create and configure custom axios instances with their own defaults, interceptors, and configuration.
96
97
```typescript { .api }
98
function create(config?: CreateAxiosDefaults): AxiosInstance;
99
100
interface AxiosInstance extends Axios {
101
<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>>;
102
<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
103
defaults: AxiosDefaults;
104
}
105
106
class Axios {
107
constructor(config?: AxiosRequestConfig);
108
defaults: AxiosDefaults;
109
interceptors: {
110
request: AxiosInterceptorManager<InternalAxiosRequestConfig>;
111
response: AxiosInterceptorManager<AxiosResponse>;
112
};
113
}
114
```
115
116
[Instance Management](./instance-management.md)
117
118
### Request Configuration
119
120
Comprehensive configuration system for customizing all aspects of HTTP requests including headers, timeouts, authentication, and more.
121
122
```typescript { .api }
123
interface AxiosRequestConfig<D = any> {
124
url?: string;
125
method?: Method;
126
baseURL?: string;
127
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
128
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
129
headers?: RawAxiosRequestHeaders | AxiosHeaders;
130
params?: any;
131
data?: D;
132
timeout?: number;
133
withCredentials?: boolean;
134
auth?: AxiosBasicCredentials;
135
responseType?: ResponseType;
136
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
137
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
138
cancelToken?: CancelToken;
139
signal?: GenericAbortSignal;
140
}
141
142
interface AxiosResponse<T = any> {
143
data: T;
144
status: number;
145
statusText: string;
146
headers: AxiosResponseHeaders;
147
config: InternalAxiosRequestConfig;
148
request?: any;
149
}
150
```
151
152
[Request Configuration](./request-configuration.md)
153
154
### Error Handling
155
156
Comprehensive error handling system with detailed error information and type-safe error checking.
157
158
```typescript { .api }
159
class AxiosError<T = unknown, D = any> extends Error {
160
constructor(
161
message?: string,
162
code?: string,
163
config?: InternalAxiosRequestConfig<D>,
164
request?: any,
165
response?: AxiosResponse<T, D>
166
);
167
168
config?: InternalAxiosRequestConfig<D>;
169
code?: string;
170
request?: any;
171
response?: AxiosResponse<T, D>;
172
isAxiosError: boolean;
173
status?: number;
174
toJSON(): object;
175
176
static from<T = unknown, D = any>(
177
error: Error | unknown,
178
code?: string,
179
config?: InternalAxiosRequestConfig<D>,
180
request?: any,
181
response?: AxiosResponse<T, D>,
182
customProps?: object
183
): AxiosError<T, D>;
184
}
185
186
function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
187
```
188
189
[Error Handling](./error-handling.md)
190
191
### Headers Management
192
193
Sophisticated HTTP headers management with the AxiosHeaders class providing type-safe header operations.
194
195
```typescript { .api }
196
class AxiosHeaders {
197
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
198
199
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean): AxiosHeaders;
200
get(headerName: string, matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
201
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
202
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
203
clear(matcher?: AxiosHeaderMatcher): boolean;
204
toJSON(asStrings?: boolean): RawAxiosHeaders;
205
206
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
207
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
208
}
209
```
210
211
[Headers Management](./headers-management.md)
212
213
### Interceptors
214
215
Request and response middleware system for automatic processing, authentication, logging, and error handling.
216
217
```typescript { .api }
218
interface AxiosInterceptorManager<V> {
219
use(
220
onFulfilled?: ((value: V) => V | Promise<V>) | null,
221
onRejected?: ((error: any) => any) | null,
222
options?: AxiosInterceptorOptions
223
): number;
224
eject(id: number): void;
225
clear(): void;
226
}
227
228
interface AxiosInterceptorOptions {
229
synchronous?: boolean;
230
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
231
}
232
```
233
234
[Interceptors](./interceptors.md)
235
236
### Request Cancellation
237
238
Request cancellation support using modern AbortController and legacy CancelToken for aborting in-flight requests.
239
240
```typescript { .api }
241
// Modern cancellation with AbortController
242
interface GenericAbortSignal {
243
readonly aborted: boolean;
244
onabort?: ((...args: any) => any) | null;
245
addEventListener?: (...args: any) => any;
246
removeEventListener?: (...args: any) => any;
247
}
248
249
// Legacy cancellation
250
class CancelToken {
251
constructor(executor: (cancel: Canceler) => void);
252
promise: Promise<Cancel>;
253
reason?: Cancel;
254
throwIfRequested(): void;
255
static source(): CancelTokenSource;
256
}
257
258
class CanceledError<T> extends AxiosError<T> {}
259
260
function isCancel(value: any): value is Cancel;
261
```
262
263
[Request Cancellation](./request-cancellation.md)
264
265
### Utility Functions
266
267
Helper functions for common operations including data transformation, configuration merging, and adapter resolution.
268
269
```typescript { .api }
270
function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
271
function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
272
function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
273
function formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
274
function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
275
function mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig;
276
```
277
278
[Utility Functions](./utility-functions.md)
279
280
## Types
281
282
```typescript { .api }
283
type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK';
284
285
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream';
286
287
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
288
289
interface RawAxiosHeaders {
290
[key: string]: AxiosHeaderValue;
291
}
292
293
interface AxiosBasicCredentials {
294
username: string;
295
password: string;
296
}
297
298
interface AxiosProxyConfig {
299
host: string;
300
port: number;
301
auth?: AxiosBasicCredentials;
302
protocol?: string;
303
}
304
305
interface AxiosProgressEvent {
306
loaded: number;
307
total?: number;
308
progress?: number;
309
bytes: number;
310
rate?: number;
311
estimated?: number;
312
upload?: boolean;
313
download?: boolean;
314
event?: any;
315
}
316
317
enum HttpStatusCode {
318
Continue = 100,
319
SwitchingProtocols = 101,
320
Processing = 102,
321
EarlyHints = 103,
322
Ok = 200,
323
Created = 201,
324
Accepted = 202,
325
NonAuthoritativeInformation = 203,
326
NoContent = 204,
327
ResetContent = 205,
328
PartialContent = 206,
329
MultiStatus = 207,
330
AlreadyReported = 208,
331
ImUsed = 226,
332
MultipleChoices = 300,
333
MovedPermanently = 301,
334
Found = 302,
335
SeeOther = 303,
336
NotModified = 304,
337
UseProxy = 305,
338
Unused = 306,
339
TemporaryRedirect = 307,
340
PermanentRedirect = 308,
341
BadRequest = 400,
342
Unauthorized = 401,
343
PaymentRequired = 402,
344
Forbidden = 403,
345
NotFound = 404,
346
MethodNotAllowed = 405,
347
NotAcceptable = 406,
348
ProxyAuthenticationRequired = 407,
349
RequestTimeout = 408,
350
Conflict = 409,
351
Gone = 410,
352
LengthRequired = 411,
353
PreconditionFailed = 412,
354
PayloadTooLarge = 413,
355
UriTooLong = 414,
356
UnsupportedMediaType = 415,
357
RangeNotSatisfiable = 416,
358
ExpectationFailed = 417,
359
ImATeapot = 418,
360
MisdirectedRequest = 421,
361
UnprocessableEntity = 422,
362
Locked = 423,
363
FailedDependency = 424,
364
TooEarly = 425,
365
UpgradeRequired = 426,
366
PreconditionRequired = 428,
367
TooManyRequests = 429,
368
RequestHeaderFieldsTooLarge = 431,
369
UnavailableForLegalReasons = 451,
370
InternalServerError = 500,
371
NotImplemented = 501,
372
BadGateway = 502,
373
ServiceUnavailable = 503,
374
GatewayTimeout = 504,
375
HttpVersionNotSupported = 505,
376
VariantAlsoNegotiates = 506,
377
InsufficientStorage = 507,
378
LoopDetected = 508,
379
NotExtended = 510,
380
NetworkAuthenticationRequired = 511
381
}
382
```