@lcap/axios-fixed 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/.husky/commit-msg +4 -0
  2. package/CHANGELOG.md +1359 -0
  3. package/LICENSE +7 -0
  4. package/MIGRATION_GUIDE.md +3 -0
  5. package/README.md +1784 -0
  6. package/dist/axios.js +4471 -0
  7. package/dist/axios.js.map +1 -0
  8. package/dist/axios.min.js +3 -0
  9. package/dist/axios.min.js.map +1 -0
  10. package/dist/browser/axios.cjs +3909 -0
  11. package/dist/browser/axios.cjs.map +1 -0
  12. package/dist/esm/axios.js +3932 -0
  13. package/dist/esm/axios.js.map +1 -0
  14. package/dist/esm/axios.min.js +3 -0
  15. package/dist/esm/axios.min.js.map +1 -0
  16. package/dist/node/axios.cjs +5242 -0
  17. package/dist/node/axios.cjs.map +1 -0
  18. package/index.d.cts +572 -0
  19. package/index.d.ts +585 -0
  20. package/index.js +43 -0
  21. package/lib/adapters/README.md +37 -0
  22. package/lib/adapters/adapters.js +126 -0
  23. package/lib/adapters/fetch.js +288 -0
  24. package/lib/adapters/http.js +895 -0
  25. package/lib/adapters/xhr.js +200 -0
  26. package/lib/axios.js +89 -0
  27. package/lib/cancel/CancelToken.js +135 -0
  28. package/lib/cancel/CanceledError.js +25 -0
  29. package/lib/cancel/isCancel.js +5 -0
  30. package/lib/core/Axios.js +240 -0
  31. package/lib/core/AxiosError.js +110 -0
  32. package/lib/core/AxiosHeaders.js +314 -0
  33. package/lib/core/InterceptorManager.js +71 -0
  34. package/lib/core/README.md +8 -0
  35. package/lib/core/buildFullPath.js +22 -0
  36. package/lib/core/dispatchRequest.js +81 -0
  37. package/lib/core/mergeConfig.js +106 -0
  38. package/lib/core/settle.js +27 -0
  39. package/lib/core/transformData.js +28 -0
  40. package/lib/defaults/index.js +161 -0
  41. package/lib/defaults/transitional.js +7 -0
  42. package/lib/env/README.md +3 -0
  43. package/lib/env/classes/FormData.js +2 -0
  44. package/lib/env/data.js +1 -0
  45. package/lib/helpers/AxiosTransformStream.js +143 -0
  46. package/lib/helpers/AxiosURLSearchParams.js +58 -0
  47. package/lib/helpers/HttpStatusCode.js +77 -0
  48. package/lib/helpers/README.md +7 -0
  49. package/lib/helpers/ZlibHeaderTransformStream.js +28 -0
  50. package/lib/helpers/bind.js +14 -0
  51. package/lib/helpers/buildURL.js +67 -0
  52. package/lib/helpers/callbackify.js +16 -0
  53. package/lib/helpers/combineURLs.js +15 -0
  54. package/lib/helpers/composeSignals.js +48 -0
  55. package/lib/helpers/cookies.js +53 -0
  56. package/lib/helpers/deprecatedMethod.js +26 -0
  57. package/lib/helpers/estimateDataURLDecodedBytes.js +73 -0
  58. package/lib/helpers/formDataToJSON.js +95 -0
  59. package/lib/helpers/formDataToStream.js +112 -0
  60. package/lib/helpers/fromDataURI.js +53 -0
  61. package/lib/helpers/isAbsoluteURL.js +15 -0
  62. package/lib/helpers/isAxiosError.js +14 -0
  63. package/lib/helpers/isURLSameOrigin.js +14 -0
  64. package/lib/helpers/null.js +2 -0
  65. package/lib/helpers/parseHeaders.js +55 -0
  66. package/lib/helpers/parseProtocol.js +6 -0
  67. package/lib/helpers/progressEventReducer.js +44 -0
  68. package/lib/helpers/readBlob.js +15 -0
  69. package/lib/helpers/resolveConfig.js +61 -0
  70. package/lib/helpers/speedometer.js +55 -0
  71. package/lib/helpers/spread.js +28 -0
  72. package/lib/helpers/throttle.js +44 -0
  73. package/lib/helpers/toFormData.js +223 -0
  74. package/lib/helpers/toURLEncodedForm.js +19 -0
  75. package/lib/helpers/trackStream.js +87 -0
  76. package/lib/helpers/validator.js +99 -0
  77. package/lib/platform/browser/classes/Blob.js +3 -0
  78. package/lib/platform/browser/classes/FormData.js +3 -0
  79. package/lib/platform/browser/classes/URLSearchParams.js +4 -0
  80. package/lib/platform/browser/index.js +13 -0
  81. package/lib/platform/common/utils.js +51 -0
  82. package/lib/platform/index.js +7 -0
  83. package/lib/platform/node/classes/FormData.js +3 -0
  84. package/lib/platform/node/classes/URLSearchParams.js +4 -0
  85. package/lib/platform/node/index.js +38 -0
  86. package/lib/utils.js +782 -0
  87. package/package.json +237 -0
package/README.md ADDED
@@ -0,0 +1,1784 @@
1
+
2
+ <h3 align="center"> 🥇 Gold sponsors <br> </h3> <table align="center" width="100%"><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://stytch.com/?utm_source&#x3D;oss-sponsorship&amp;utm_medium&#x3D;paid_sponsorship&amp;utm_content&#x3D;website-link&amp;utm_campaign&#x3D;axios-http" style="padding: 10px; display: inline-block" target="_blank"> <picture> <source width="200px" height="38px" media="(prefers-color-scheme: dark)" srcset="https://axios-http.com/assets/sponsors/stytch_white.png"> <img width="200px" height="38px" src="https://axios-http.com/assets/sponsors/stytch.png" alt="Stytch"/> </picture> </a> <p align="center" title="API-first authentication, authorization, and fraud prevention">API-first authentication, authorization, and fraud prevention</p> <p align="center"> <a href="https://stytch.com/?utm_source&#x3D;oss-sponsorship&amp;utm_medium&#x3D;paid_sponsorship&amp;utm_content&#x3D;website-link&amp;utm_campaign&#x3D;axios-http" target="_blank"><b>Website</b></a> | <a href="https://stytch.com/docs?utm_source&#x3D;oss-sponsorship&amp;utm_medium&#x3D;paid_sponsorship&amp;utm_content&#x3D;docs-link&amp;utm_campaign&#x3D;axios-http" target="_blank"><b>Documentation</b></a> | <a href="https://github.com/stytchauth/stytch-node?utm_source&#x3D;oss-sponsorship&amp;utm_medium&#x3D;paid_sponsorship&amp;utm_content&#x3D;node-sdk&amp;utm_campaign&#x3D;axios-http" target="_blank"><b>Node.js</b></a> </p>
3
+ </td><td align="center" width="33.333333333333336%"> <a href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="133px" height="43px" src="https://axios-http.com/assets/sponsors/principal.svg" alt="Principal Financial Group"/> </a> <p align="center" title="We’re bound by one common purpose: to give you the financial tools, resources and information you need to live your best life.">We’re bound by one common purpose: to give you the financial tools, resources and information you ne...</p> <p align="center"> <a href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>www.principal.com</b></a> </p>
4
+ </td><td align="center" width="33.333333333333336%"> <a href="https://twicsy.com/buy-instagram-followers?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="85px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/dfa9670ad5e66eea17315332453c7f4e3a3b5905.png" alt="Buy Instagram Followers Twicsy"/> </a> <p align="center" title="Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site to buy followers from the likes of US Magazine.">Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site...</p> <p align="center"> <a href="https://twicsy.com/buy-instagram-followers?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>twicsy.com</b></a> </p>
5
+ </td></tr><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <picture> <source width="200px" height="52px" media="(prefers-color-scheme: dark)" srcset="https://axios-http.com/assets/sponsors/descope_white.png"> <img width="200px" height="52px" src="https://axios-http.com/assets/sponsors/descope.png" alt="Descope"/> </picture> </a> <p align="center" title="Hi, we&#x27;re Descope! We are building something in the authentication space for app developers and can’t wait to place it in your hands.">Hi, we&#x27;re Descope! We are building something in the authentication space for app developers and...</p> <p align="center"> <a href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" target="_blank"><b>Website</b></a> | <a href="https://docs.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" target="_blank"><b>Docs</b></a> | <a href="https://www.descope.com/community?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" target="_blank"><b>Community</b></a> </p>
6
+ </td><td align="center" width="33.333333333333336%"> <a href="https://route4me.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <picture> <source width="200px" height="51px" media="(prefers-color-scheme: dark)" srcset="https://axios-http.com/assets/sponsors/route4me_white.png"> <img width="200px" height="51px" src="https://axios-http.com/assets/sponsors/route4me.png" alt="Route4Me"/> </picture> </a> <p align="center" title="Best Route Planning And Route Optimization Software">Best Route Planning And Route Optimization Software</p> <p align="center"> <a href="https://route4me.com/platform/route-optimization-software?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>Explore</b></a> | <a href="https://route4me.com/platform/marketplace/pricing?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>Free Trial</b></a> | <a href="https://route4me.com/contact?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>Contact</b></a> </p>
7
+ </td><td align="center" width="33.333333333333336%"> <a href="https://buzzoid.com/buy-instagram-followers/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="62px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/e1625cb54e10ee40180c99d1495a462e9d6664a4.png" alt="Buzzoid - Buy Instagram Followers"/> </a> <p align="center" title="At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rated world&#x27;s #1 IG service since 2012.">At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rate...</p> <p align="center"> <a href="https://buzzoid.com/buy-instagram-followers/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>buzzoid.com</b></a> </p>
8
+ </td></tr><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="70px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/e699ec99f7df3a203ddbc49d3c7712a907e628ea.png" alt="Poprey - Buy Instagram Likes"/> </a> <p align="center" title="Buy Instagram Likes">Buy Instagram Likes</p> <p align="center"> <a href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>poprey.com</b></a> </p>
9
+ </td><td align="center" width="33.333333333333336%"> <a href="https://requestly.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="71px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/16450b4dc0deb9dab5a511bf2bc8b8b4ac33412f.png" alt="Requestly"/> </a> <p align="center" title="A lightweight open-source API Development, Testing &amp; Mocking platform">A lightweight open-source API Development, Testing &amp; Mocking platform</p> <p align="center"> <a href="https://requestly.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>requestly.com</b></a> </p>
10
+ </td><td align="center" width="33.333333333333336%"> <a href="https://opencollective.com/axios/contribute" target="_blank" >💜 Become a sponsor</a>
11
+ </td></tr></table>
12
+
13
+ <!--<div>marker</div>-->
14
+ <br><br>
15
+ <div align="center">
16
+ <a href="https://axios-http.com"><img src="https://axios-http.com/assets/logo.svg" alt="Axios" /></a><br>
17
+ </div>
18
+
19
+ <p align="center">Promise based HTTP client for the browser and node.js</p>
20
+
21
+ <p align="center">
22
+ <a href="https://axios-http.com/"><b>Website</b></a> •
23
+ <a href="https://axios-http.com/docs/intro"><b>Documentation</b></a>
24
+ </p>
25
+
26
+ <div align="center">
27
+
28
+ [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
29
+ [![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
30
+ [![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)
31
+ [![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)
32
+ [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
33
+ [![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)
34
+ [![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest)
35
+ [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios)
36
+ [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
37
+ [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
38
+ [![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios)
39
+ [![Contributors](https://img.shields.io/github/contributors/axios/axios.svg?style=flat-square)](CONTRIBUTORS.md)
40
+
41
+
42
+
43
+
44
+ </div>
45
+
46
+ ## Table of Contents
47
+
48
+ - [Features](#features)
49
+ - [Browser Support](#browser-support)
50
+ - [Installing](#installing)
51
+ - [Package manager](#package-manager)
52
+ - [CDN](#cdn)
53
+ - [Example](#example)
54
+ - [Axios API](#axios-api)
55
+ - [Request method aliases](#request-method-aliases)
56
+ - [Concurrency 👎](#concurrency-deprecated)
57
+ - [Creating an instance](#creating-an-instance)
58
+ - [Instance methods](#instance-methods)
59
+ - [Request Config](#request-config)
60
+ - [Response Schema](#response-schema)
61
+ - [Config Defaults](#config-defaults)
62
+ - [Global axios defaults](#global-axios-defaults)
63
+ - [Custom instance defaults](#custom-instance-defaults)
64
+ - [Config order of precedence](#config-order-of-precedence)
65
+ - [Interceptors](#interceptors)
66
+ - [Multiple Interceptors](#multiple-interceptors)
67
+ - [Handling Errors](#handling-errors)
68
+ - [Cancellation](#cancellation)
69
+ - [AbortController](#abortcontroller)
70
+ - [CancelToken 👎](#canceltoken-deprecated)
71
+ - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
72
+ - [URLSearchParams](#urlsearchparams)
73
+ - [Query string](#query-string-older-browsers)
74
+ - [🆕 Automatic serialization](#-automatic-serialization-to-urlsearchparams)
75
+ - [Using multipart/form-data format](#using-multipartform-data-format)
76
+ - [FormData](#formdata)
77
+ - [🆕 Automatic serialization](#-automatic-serialization-to-formdata)
78
+ - [Files Posting](#files-posting)
79
+ - [HTML Form Posting](#-html-form-posting-browser)
80
+ - [🆕 Progress capturing](#-progress-capturing)
81
+ - [🆕 Rate limiting](#-rate-limiting)
82
+ - [🆕 AxiosHeaders](#-axiosheaders)
83
+ - [🔥 Fetch adapter](#-fetch-adapter)
84
+ - [🔥 Custom fetch](#-custom-fetch)
85
+ - [🔥 Using with Tauri](#-using-with-tauri)
86
+ - [🔥 Using with SvelteKit](#-using-with-sveltekit-)
87
+ - [🔥 HTTP2](#-http2)
88
+ - [Semver](#semver)
89
+ - [Promises](#promises)
90
+ - [TypeScript](#typescript)
91
+ - [Resources](#resources)
92
+ - [Credits](#credits)
93
+ - [License](#license)
94
+
95
+ ## Features
96
+
97
+ - **Browser Requests:** Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) directly from the browser.
98
+ - **Node.js Requests:** Make [http](https://nodejs.org/api/http.html) requests from Node.js environments.
99
+ - **Promise-based:** Fully supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API for easier asynchronous code.
100
+ - **Interceptors:** Intercept requests and responses to add custom logic or transform data.
101
+ - **Data Transformation:** Transform request and response data automatically.
102
+ - **Request Cancellation:** Cancel requests using built-in mechanisms.
103
+ - **Automatic JSON Handling:** Automatically serializes and parses [JSON](https://www.json.org/json-en.html) data.
104
+ - **Form Serialization:** 🆕 Automatically serializes data objects to `multipart/form-data` or `x-www-form-urlencoded` formats.
105
+ - **XSRF Protection:** Client-side support to protect against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery).
106
+
107
+ ## Browser Support
108
+
109
+ | Chrome | Firefox | Safari | Opera | Edge |
110
+ |:------:|:-------:|:------:|:-----:|:----:|
111
+ | ![Chrome browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) |
112
+ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
113
+
114
+ [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
115
+
116
+ ## Installing
117
+
118
+ ### Package manager
119
+
120
+ Using npm:
121
+
122
+ ```bash
123
+ $ npm install axios
124
+ ```
125
+
126
+ Using bower:
127
+
128
+ ```bash
129
+ $ bower install axios
130
+ ```
131
+
132
+ Using yarn:
133
+
134
+ ```bash
135
+ $ yarn add axios
136
+ ```
137
+
138
+ Using pnpm:
139
+
140
+ ```bash
141
+ $ pnpm add axios
142
+ ```
143
+
144
+ Using bun:
145
+
146
+ ```bash
147
+ $ bun add axios
148
+ ```
149
+
150
+ Once the package is installed, you can import the library using `import` or `require` approach:
151
+
152
+ ```js
153
+ import axios, {isCancel, AxiosError} from 'axios';
154
+ ```
155
+
156
+ You can also use the default export, since the named export is just a re-export from the Axios factory:
157
+
158
+ ```js
159
+ import axios from 'axios';
160
+
161
+ console.log(axios.isCancel('something'));
162
+ ````
163
+
164
+ If you use `require` for importing, **only default export is available**:
165
+
166
+ ```js
167
+ const axios = require('axios');
168
+
169
+ console.log(axios.isCancel('something'));
170
+ ```
171
+
172
+ For some bundlers and some ES6 linters you may need to do the following:
173
+
174
+ ```js
175
+ import { default as axios } from 'axios';
176
+ ```
177
+
178
+ For cases where something went wrong when trying to import a module into a custom or legacy environment,
179
+ you can try importing the module package directly:
180
+
181
+ ```js
182
+ const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
183
+ // const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
184
+ ```
185
+
186
+ ### CDN
187
+
188
+ Using jsDelivr CDN (ES5 UMD browser module):
189
+
190
+ ```html
191
+ <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
192
+ ```
193
+
194
+ Using unpkg CDN:
195
+
196
+ ```html
197
+ <script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>
198
+ ```
199
+
200
+ ## Example
201
+
202
+ > **Note**: CommonJS usage
203
+ > In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:
204
+
205
+ ```js
206
+ import axios from 'axios';
207
+ //const axios = require('axios'); // legacy way
208
+
209
+ // Make a request for a user with a given ID
210
+ axios.get('/user?ID=12345')
211
+ .then(function (response) {
212
+ // handle success
213
+ console.log(response);
214
+ })
215
+ .catch(function (error) {
216
+ // handle error
217
+ console.log(error);
218
+ })
219
+ .finally(function () {
220
+ // always executed
221
+ });
222
+
223
+ // Optionally the request above could also be done as
224
+ axios.get('/user', {
225
+ params: {
226
+ ID: 12345
227
+ }
228
+ })
229
+ .then(function (response) {
230
+ console.log(response);
231
+ })
232
+ .catch(function (error) {
233
+ console.log(error);
234
+ })
235
+ .finally(function () {
236
+ // always executed
237
+ });
238
+
239
+ // Want to use async/await? Add the `async` keyword to your outer function/method.
240
+ async function getUser() {
241
+ try {
242
+ const response = await axios.get('/user?ID=12345');
243
+ console.log(response);
244
+ } catch (error) {
245
+ console.error(error);
246
+ }
247
+ }
248
+ ```
249
+
250
+ > **Note**: `async/await` is part of ECMAScript 2017 and is not supported in Internet
251
+ > Explorer and older browsers, so use with caution.
252
+
253
+ Performing a `POST` request
254
+
255
+ ```js
256
+ axios.post('/user', {
257
+ firstName: 'Fred',
258
+ lastName: 'Flintstone'
259
+ })
260
+ .then(function (response) {
261
+ console.log(response);
262
+ })
263
+ .catch(function (error) {
264
+ console.log(error);
265
+ });
266
+ ```
267
+
268
+ Performing multiple concurrent requests
269
+
270
+ ```js
271
+ function getUserAccount() {
272
+ return axios.get('/user/12345');
273
+ }
274
+
275
+ function getUserPermissions() {
276
+ return axios.get('/user/12345/permissions');
277
+ }
278
+
279
+ Promise.all([getUserAccount(), getUserPermissions()])
280
+ .then(function (results) {
281
+ const acct = results[0];
282
+ const perm = results[1];
283
+ });
284
+ ```
285
+
286
+ ## axios API
287
+
288
+ Requests can be made by passing the relevant config to `axios`.
289
+
290
+ ##### axios(config)
291
+
292
+ ```js
293
+ // Send a POST request
294
+ axios({
295
+ method: 'post',
296
+ url: '/user/12345',
297
+ data: {
298
+ firstName: 'Fred',
299
+ lastName: 'Flintstone'
300
+ }
301
+ });
302
+ ```
303
+
304
+ ```js
305
+ // GET request for remote image in node.js
306
+ axios({
307
+ method: 'get',
308
+ url: 'https://bit.ly/2mTM3nY',
309
+ responseType: 'stream'
310
+ })
311
+ .then(function (response) {
312
+ response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
313
+ });
314
+ ```
315
+
316
+ ##### axios(url[, config])
317
+
318
+ ```js
319
+ // Send a GET request (default method)
320
+ axios('/user/12345');
321
+ ```
322
+
323
+ ### Request method aliases
324
+
325
+ For convenience, aliases have been provided for all common request methods.
326
+
327
+ ##### axios.request(config)
328
+ ##### axios.get(url[, config])
329
+ ##### axios.delete(url[, config])
330
+ ##### axios.head(url[, config])
331
+ ##### axios.options(url[, config])
332
+ ##### axios.post(url[, data[, config]])
333
+ ##### axios.put(url[, data[, config]])
334
+ ##### axios.patch(url[, data[, config]])
335
+
336
+ ###### NOTE
337
+ When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
338
+
339
+ ### Concurrency (Deprecated)
340
+ Please use `Promise.all` to replace the below functions.
341
+
342
+ Helper functions for dealing with concurrent requests.
343
+
344
+ axios.all(iterable)
345
+ axios.spread(callback)
346
+
347
+ ### Creating an instance
348
+
349
+ You can create a new instance of axios with a custom config.
350
+
351
+ ##### axios.create([config])
352
+
353
+ ```js
354
+ const instance = axios.create({
355
+ baseURL: 'https://some-domain.com/api/',
356
+ timeout: 1000,
357
+ headers: {'X-Custom-Header': 'foobar'}
358
+ });
359
+ ```
360
+
361
+ ### Instance methods
362
+
363
+ The available instance methods are listed below. The specified config will be merged with the instance config.
364
+
365
+ ##### axios#request(config)
366
+ ##### axios#get(url[, config])
367
+ ##### axios#delete(url[, config])
368
+ ##### axios#head(url[, config])
369
+ ##### axios#options(url[, config])
370
+ ##### axios#post(url[, data[, config]])
371
+ ##### axios#put(url[, data[, config]])
372
+ ##### axios#patch(url[, data[, config]])
373
+ ##### axios#getUri([config])
374
+
375
+ ## Request Config
376
+
377
+ These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
378
+
379
+ ```js
380
+ {
381
+ // `url` is the server URL that will be used for the request
382
+ url: '/user',
383
+
384
+ // `method` is the request method to be used when making the request
385
+ method: 'get', // default
386
+
387
+ // `baseURL` will be prepended to `url` unless `url` is absolute and option `allowAbsoluteUrls` is set to true.
388
+ // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
389
+ // to methods of that instance.
390
+ baseURL: 'https://some-domain.com/api/',
391
+
392
+ // `allowAbsoluteUrls` determines whether or not absolute URLs will override a configured `baseUrl`.
393
+ // When set to true (default), absolute values for `url` will override `baseUrl`.
394
+ // When set to false, absolute values for `url` will always be prepended by `baseUrl`.
395
+ allowAbsoluteUrls: true,
396
+
397
+ // `transformRequest` allows changes to the request data before it is sent to the server
398
+ // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
399
+ // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
400
+ // FormData or Stream
401
+ // You may modify the headers object.
402
+ transformRequest: [function (data, headers) {
403
+ // Do whatever you want to transform the data
404
+
405
+ return data;
406
+ }],
407
+
408
+ // `transformResponse` allows changes to the response data to be made before
409
+ // it is passed to then/catch
410
+ transformResponse: [function (data) {
411
+ // Do whatever you want to transform the data
412
+
413
+ return data;
414
+ }],
415
+
416
+ // `headers` are custom headers to be sent
417
+ headers: {'X-Requested-With': 'XMLHttpRequest'},
418
+
419
+ // `params` are the URL parameters to be sent with the request
420
+ // Must be a plain object or a URLSearchParams object
421
+ params: {
422
+ ID: 12345
423
+ },
424
+
425
+ // `paramsSerializer` is an optional config that allows you to customize serializing `params`.
426
+ paramsSerializer: {
427
+
428
+ // Custom encoder function which sends key/value pairs in an iterative fashion.
429
+ encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },
430
+
431
+ // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
432
+ serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
433
+
434
+ // Configuration for formatting array indexes in the params.
435
+ indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).
436
+ },
437
+
438
+ // `data` is the data to be sent as the request body
439
+ // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
440
+ // When no `transformRequest` is set, must be of one of the following types:
441
+ // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
442
+ // - Browser only: FormData, File, Blob
443
+ // - Node only: Stream, Buffer, FormData (form-data package)
444
+ data: {
445
+ firstName: 'Fred'
446
+ },
447
+
448
+ // syntax alternative to send data into the body
449
+ // method post
450
+ // only the value is sent, not the key
451
+ data: 'Country=Brasil&City=Belo Horizonte',
452
+
453
+ // `timeout` specifies the number of milliseconds before the request times out.
454
+ // If the request takes longer than `timeout`, the request will be aborted.
455
+ timeout: 1000, // default is `0` (no timeout)
456
+
457
+ // `withCredentials` indicates whether or not cross-site Access-Control requests
458
+ // should be made using credentials
459
+ withCredentials: false, // default
460
+
461
+ // `adapter` allows custom handling of requests which makes testing easier.
462
+ // Return a promise and supply a valid response (see lib/adapters/README.md)
463
+ adapter: function (config) {
464
+ /* ... */
465
+ },
466
+ // Also, you can set the name of the built-in adapter, or provide an array with their names
467
+ // to choose the first available in the environment
468
+ adapter: 'xhr', // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
469
+
470
+ // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
471
+ // This will set an `Authorization` header, overwriting any existing
472
+ // `Authorization` custom headers you have set using `headers`.
473
+ // Please note that only HTTP Basic auth is configurable through this parameter.
474
+ // For Bearer tokens and such, use `Authorization` custom headers instead.
475
+ auth: {
476
+ username: 'janedoe',
477
+ password: 's00pers3cret'
478
+ },
479
+
480
+ // `responseType` indicates the type of data that the server will respond with
481
+ // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
482
+ // browser only: 'blob'
483
+ responseType: 'json', // default
484
+
485
+ // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
486
+ // Note: Ignored for `responseType` of 'stream' or client-side requests
487
+ // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
488
+ // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
489
+ // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
490
+ responseEncoding: 'utf8', // default
491
+
492
+ // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
493
+ xsrfCookieName: 'XSRF-TOKEN', // default
494
+
495
+ // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
496
+ xsrfHeaderName: 'X-XSRF-TOKEN', // default
497
+
498
+ // `undefined` (default) - set XSRF header only for the same origin requests
499
+ withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),
500
+
501
+ // `onUploadProgress` allows handling of progress events for uploads
502
+ // browser & node.js
503
+ onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
504
+ // Do whatever you want with the Axios progress event
505
+ },
506
+
507
+ // `onDownloadProgress` allows handling of progress events for downloads
508
+ // browser & node.js
509
+ onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
510
+ // Do whatever you want with the Axios progress event
511
+ },
512
+
513
+ // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
514
+ maxContentLength: 2000,
515
+
516
+ // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
517
+ maxBodyLength: 2000,
518
+
519
+ // `validateStatus` defines whether to resolve or reject the promise for a given
520
+ // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
521
+ // or `undefined`), the promise will be resolved; otherwise, the promise will be
522
+ // rejected.
523
+ validateStatus: function (status) {
524
+ return status >= 200 && status < 300; // default
525
+ },
526
+
527
+ // `maxRedirects` defines the maximum number of redirects to follow in node.js.
528
+ // If set to 0, no redirects will be followed.
529
+ maxRedirects: 21, // default
530
+
531
+ // `beforeRedirect` defines a function that will be called before redirect.
532
+ // Use this to adjust the request options upon redirecting,
533
+ // to inspect the latest response headers,
534
+ // or to cancel the request by throwing an error
535
+ // If maxRedirects is set to 0, `beforeRedirect` is not used.
536
+ beforeRedirect: (options, { headers }) => {
537
+ if (options.hostname === "example.com") {
538
+ options.auth = "user:password";
539
+ }
540
+ },
541
+
542
+ // `socketPath` defines a UNIX Socket to be used in node.js.
543
+ // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
544
+ // Only either `socketPath` or `proxy` can be specified.
545
+ // If both are specified, `socketPath` is used.
546
+ socketPath: null, // default
547
+
548
+ // `transport` determines the transport method that will be used to make the request.
549
+ // If defined, it will be used. Otherwise, if `maxRedirects` is 0,
550
+ // the default `http` or `https` library will be used, depending on the protocol specified in `protocol`.
551
+ // Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol,
552
+ // which can handle redirects.
553
+ transport: undefined, // default
554
+
555
+ // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
556
+ // and https requests, respectively, in node.js. This allows options to be added like
557
+ // `keepAlive` that are not enabled by default before Node.js v19.0.0. After Node.js
558
+ // v19.0.0, you no longer need to customize the agent to enable `keepAlive` because
559
+ // `http.globalAgent` has `keepAlive` enabled by default.
560
+ httpAgent: new http.Agent({ keepAlive: true }),
561
+ httpsAgent: new https.Agent({ keepAlive: true }),
562
+
563
+ // `proxy` defines the hostname, port, and protocol of the proxy server.
564
+ // You can also define your proxy using the conventional `http_proxy` and
565
+ // `https_proxy` environment variables. If you are using environment variables
566
+ // for your proxy configuration, you can also define a `no_proxy` environment
567
+ // variable as a comma-separated list of domains that should not be proxied.
568
+ // Use `false` to disable proxies, ignoring environment variables.
569
+ // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
570
+ // supplies credentials.
571
+ // This will set an `Proxy-Authorization` header, overwriting any existing
572
+ // `Proxy-Authorization` custom headers you have set using `headers`.
573
+ // If the proxy server uses HTTPS, then you must set the protocol to `https`.
574
+ proxy: {
575
+ protocol: 'https',
576
+ host: '127.0.0.1',
577
+ // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
578
+ port: 9000,
579
+ auth: {
580
+ username: 'mikeymike',
581
+ password: 'rapunz3l'
582
+ }
583
+ },
584
+
585
+ // `cancelToken` specifies a cancel token that can be used to cancel the request
586
+ // (see Cancellation section below for details)
587
+ cancelToken: new CancelToken(function (cancel) {
588
+ }),
589
+
590
+ // an alternative way to cancel Axios requests using AbortController
591
+ signal: new AbortController().signal,
592
+
593
+ // `decompress` indicates whether or not the response body should be decompressed
594
+ // automatically. If set to `true` will also remove the 'content-encoding' header
595
+ // from the responses objects of all decompressed responses
596
+ // - Node only (XHR cannot turn off decompression)
597
+ decompress: true, // default
598
+
599
+ // `insecureHTTPParser` boolean.
600
+ // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
601
+ // This may allow interoperability with non-conformant HTTP implementations.
602
+ // Using the insecure parser should be avoided.
603
+ // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
604
+ // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
605
+ insecureHTTPParser: undefined, // default
606
+
607
+ // transitional options for backward compatibility that may be removed in the newer versions
608
+ transitional: {
609
+ // silent JSON parsing mode
610
+ // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
611
+ // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
612
+ silentJSONParsing: true, // default value for the current Axios version
613
+
614
+ // try to parse the response string as JSON even if `responseType` is not 'json'
615
+ forcedJSONParsing: true,
616
+
617
+ // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
618
+ clarifyTimeoutError: false,
619
+ },
620
+
621
+ env: {
622
+ // The FormData class to be used to automatically serialize the payload into a FormData object
623
+ FormData: window?.FormData || global?.FormData
624
+ },
625
+
626
+ formSerializer: {
627
+ visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
628
+ dots: boolean; // use dots instead of brackets format
629
+ metaTokens: boolean; // keep special endings like {} in parameter key
630
+ indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
631
+ },
632
+
633
+ // http adapter only (node.js)
634
+ maxRate: [
635
+ 100 * 1024, // 100KB/s upload limit,
636
+ 100 * 1024 // 100KB/s download limit
637
+ ]
638
+ }
639
+ ```
640
+
641
+ ## Response Schema
642
+
643
+ The response for a request contains the following information.
644
+
645
+ ```js
646
+ {
647
+ // `data` is the response that was provided by the server
648
+ data: {},
649
+
650
+ // `status` is the HTTP status code from the server response
651
+ status: 200,
652
+
653
+ // `statusText` is the HTTP status message from the server response
654
+ statusText: 'OK',
655
+
656
+ // `headers` the HTTP headers that the server responded with
657
+ // All header names are lowercase and can be accessed using the bracket notation.
658
+ // Example: `response.headers['content-type']`
659
+ headers: {},
660
+
661
+ // `config` is the config that was provided to `axios` for the request
662
+ config: {},
663
+
664
+ // `request` is the request that generated this response
665
+ // It is the last ClientRequest instance in node.js (in redirects)
666
+ // and an XMLHttpRequest instance in the browser
667
+ request: {}
668
+ }
669
+ ```
670
+
671
+ When using `then`, you will receive the response as follows:
672
+
673
+ ```js
674
+ axios.get('/user/12345')
675
+ .then(function (response) {
676
+ console.log(response.data);
677
+ console.log(response.status);
678
+ console.log(response.statusText);
679
+ console.log(response.headers);
680
+ console.log(response.config);
681
+ });
682
+ ```
683
+
684
+ 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.
685
+
686
+ ## Config Defaults
687
+
688
+ You can specify config defaults that will be applied to every request.
689
+
690
+ ### Global axios defaults
691
+
692
+ ```js
693
+ axios.defaults.baseURL = 'https://api.example.com';
694
+
695
+ // Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
696
+ // See below for an example using Custom instance defaults instead.
697
+ axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
698
+
699
+ axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
700
+ ```
701
+
702
+ ### Custom instance defaults
703
+
704
+ ```js
705
+ // Set config defaults when creating the instance
706
+ const instance = axios.create({
707
+ baseURL: 'https://api.example.com'
708
+ });
709
+
710
+ // Alter defaults after instance has been created
711
+ instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
712
+ ```
713
+
714
+ ### Config order of precedence
715
+
716
+ Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults/index.js](https://github.com/axios/axios/blob/main/lib/defaults/index.js#L49), 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.
717
+
718
+ ```js
719
+ // Create an instance using the config defaults provided by the library
720
+ // At this point the timeout config value is `0` as is the default for the library
721
+ const instance = axios.create();
722
+
723
+ // Override timeout default for the library
724
+ // Now all requests using this instance will wait 2.5 seconds before timing out
725
+ instance.defaults.timeout = 2500;
726
+
727
+ // Override timeout for this request as it's known to take a long time
728
+ instance.get('/longRequest', {
729
+ timeout: 5000
730
+ });
731
+ ```
732
+
733
+ ## Interceptors
734
+
735
+ You can intercept requests or responses before they are handled by `then` or `catch`.
736
+
737
+ ```js
738
+
739
+ const instance = axios.create();
740
+
741
+ // Add a request interceptor
742
+ instance.interceptors.request.use(function (config) {
743
+ // Do something before request is sent
744
+ return config;
745
+ }, function (error) {
746
+ // Do something with request error
747
+ return Promise.reject(error);
748
+ });
749
+
750
+ // Add a response interceptor
751
+ instance.interceptors.response.use(function (response) {
752
+ // Any status code that lie within the range of 2xx cause this function to trigger
753
+ // Do something with response data
754
+ return response;
755
+ }, function (error) {
756
+ // Any status codes that falls outside the range of 2xx cause this function to trigger
757
+ // Do something with response error
758
+ return Promise.reject(error);
759
+ });
760
+ ```
761
+
762
+ If you need to remove an interceptor later you can.
763
+
764
+ ```js
765
+ const instance = axios.create();
766
+ const myInterceptor = instance.interceptors.request.use(function () {/*...*/});
767
+ axios.interceptors.request.eject(myInterceptor);
768
+ ```
769
+
770
+ You can also clear all interceptors for requests or responses.
771
+ ```js
772
+ const instance = axios.create();
773
+ instance.interceptors.request.use(function () {/*...*/});
774
+ instance.interceptors.request.clear(); // Removes interceptors from requests
775
+ instance.interceptors.response.use(function () {/*...*/});
776
+ instance.interceptors.response.clear(); // Removes interceptors from responses
777
+ ```
778
+
779
+ You can add interceptors to a custom instance of axios.
780
+
781
+ ```js
782
+ const instance = axios.create();
783
+ instance.interceptors.request.use(function () {/*...*/});
784
+ ```
785
+
786
+ When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
787
+ in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
788
+ 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
789
+ to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
790
+
791
+ ```js
792
+ axios.interceptors.request.use(function (config) {
793
+ config.headers.test = 'I am only a header!';
794
+ return config;
795
+ }, null, { synchronous: true });
796
+ ```
797
+
798
+ If you want to execute a particular interceptor based on a runtime check,
799
+ you can add a `runWhen` function to the options object. The request interceptor will not be executed **if and only if** the return
800
+ of `runWhen` is `false`. The function will be called with the config
801
+ object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
802
+ asynchronous request interceptor that only needs to run at certain times.
803
+
804
+ ```js
805
+ function onGetCall(config) {
806
+ return config.method === 'get';
807
+ }
808
+ axios.interceptors.request.use(function (config) {
809
+ config.headers.test = 'special get headers';
810
+ return config;
811
+ }, null, { runWhen: onGetCall });
812
+ ```
813
+
814
+ > **Note:** options parameter(having `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment.
815
+
816
+ ### Multiple Interceptors
817
+
818
+ Given you add multiple response interceptors
819
+ and when the response was fulfilled
820
+ - then each interceptor is executed
821
+ - then they are executed in the order they were added
822
+ - then only the last interceptor's result is returned
823
+ - then every interceptor receives the result of its predecessor
824
+ - and when the fulfillment-interceptor throws
825
+ - then the following fulfillment-interceptor is not called
826
+ - then the following rejection-interceptor is called
827
+ - once caught, another following fulfill-interceptor is called again (just like in a promise chain).
828
+
829
+ Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.
830
+
831
+ ## Error Types
832
+
833
+ There are many different axios error messages that can appear that can provide basic information about the specifics of the error and where opportunities may lie in debugging.
834
+
835
+ The general structure of axios errors is as follows:
836
+ | Property | Definition |
837
+ | -------- | ---------- |
838
+ | message | A quick summary of the error message and the status it failed with. |
839
+ | name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. |
840
+ | stack | Provides the stack trace of the error. |
841
+ | config | An axios config object with specific instance configurations defined by the user from when the request was made |
842
+ | code | Represents an axios identified error. The table below lists out specific definitions for internal axios error. |
843
+ | status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings.
844
+
845
+ Below is a list of potential axios identified error:
846
+
847
+ | Code | Definition |
848
+ | --- | --- |
849
+ | ERR_BAD_OPTION_VALUE | Invalid value provided in axios configuration. |
850
+ | ERR_BAD_OPTION | Invalid option provided in axios configuration. |
851
+ | ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. |
852
+ | ERR_DEPRECATED | Deprecated feature or method used in axios. |
853
+ | ERR_INVALID_URL | Invalid URL provided for axios request. |
854
+ | ECONNABORTED | Typically indicates that the request has been timed out (unless `transitional.clarifyTimeoutError` is set) or aborted by the browser or its plugin. |
855
+ | ERR_CANCELED | Feature or method is canceled explicitly by the user using an AbortSignal (or a CancelToken). |
856
+ | ETIMEDOUT | Request timed out due to exceeding default axios timelimit. `transitional.clarifyTimeoutError` must be set to `true`, otherwise a generic `ECONNABORTED` error will be thrown instead. |
857
+ | ERR_NETWORK | Network-related issue. In the browser, this error can also be caused by a [CORS](https://developer.mozilla.org/ru/docs/Web/HTTP/Guides/CORS) or [Mixed Content](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content) policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console. |
858
+ | ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration. |
859
+ | ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with `5xx` status code. |
860
+ | ERR_BAD_REQUEST | The request has an unexpected format or is missing required parameters. Usually related to a response with `4xx` status code. |
861
+
862
+ ## Handling Errors
863
+
864
+ 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.
865
+
866
+ ```js
867
+ axios.get('/user/12345')
868
+ .catch(function (error) {
869
+ if (error.response) {
870
+ // The request was made and the server responded with a status code
871
+ // that falls out of the range of 2xx
872
+ console.log(error.response.data);
873
+ console.log(error.response.status);
874
+ console.log(error.response.headers);
875
+ } else if (error.request) {
876
+ // The request was made but no response was received
877
+ // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
878
+ // http.ClientRequest in node.js
879
+ console.log(error.request);
880
+ } else {
881
+ // Something happened in setting up the request that triggered an Error
882
+ console.log('Error', error.message);
883
+ }
884
+ console.log(error.config);
885
+ });
886
+ ```
887
+
888
+ 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.
889
+
890
+ ```js
891
+ axios.get('/user/12345', {
892
+ validateStatus: function (status) {
893
+ return status < 500; // Resolve only if the status code is less than 500
894
+ }
895
+ })
896
+ ```
897
+
898
+ Using `toJSON` you get an object with more information about the HTTP error.
899
+
900
+ ```js
901
+ axios.get('/user/12345')
902
+ .catch(function (error) {
903
+ console.log(error.toJSON());
904
+ });
905
+ ```
906
+
907
+ ## Cancellation
908
+
909
+ ### AbortController
910
+
911
+ Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:
912
+
913
+ ```js
914
+ const controller = new AbortController();
915
+
916
+ axios.get('/foo/bar', {
917
+ signal: controller.signal
918
+ }).then(function(response) {
919
+ //...
920
+ });
921
+ // cancel the request
922
+ controller.abort()
923
+ ```
924
+
925
+ ### CancelToken `👎deprecated`
926
+
927
+ You can also cancel a request using a *CancelToken*.
928
+
929
+ > The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
930
+
931
+ > This API is deprecated since v0.22.0 and shouldn't be used in new projects
932
+
933
+ You can create a cancel token using the `CancelToken.source` factory as shown below:
934
+
935
+ ```js
936
+ const CancelToken = axios.CancelToken;
937
+ const source = CancelToken.source();
938
+
939
+ axios.get('/user/12345', {
940
+ cancelToken: source.token
941
+ }).catch(function (thrown) {
942
+ if (axios.isCancel(thrown)) {
943
+ console.log('Request canceled', thrown.message);
944
+ } else {
945
+ // handle error
946
+ }
947
+ });
948
+
949
+ axios.post('/user/12345', {
950
+ name: 'new name'
951
+ }, {
952
+ cancelToken: source.token
953
+ })
954
+
955
+ // cancel the request (the message parameter is optional)
956
+ source.cancel('Operation canceled by the user.');
957
+ ```
958
+
959
+ You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
960
+
961
+ ```js
962
+ const CancelToken = axios.CancelToken;
963
+ let cancel;
964
+
965
+ axios.get('/user/12345', {
966
+ cancelToken: new CancelToken(function executor(c) {
967
+ // An executor function receives a cancel function as a parameter
968
+ cancel = c;
969
+ })
970
+ });
971
+
972
+ // cancel the request
973
+ cancel();
974
+ ```
975
+
976
+ > **Note:** you can cancel several requests with the same cancel token/abort controller.
977
+ > 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.
978
+
979
+ > During the transition period, you can use both cancellation APIs, even for the same request:
980
+
981
+ ## Using `application/x-www-form-urlencoded` format
982
+
983
+ ### URLSearchParams
984
+
985
+ 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).
986
+
987
+ ```js
988
+ const params = new URLSearchParams({ foo: 'bar' });
989
+ params.append('extraparam', 'value');
990
+ axios.post('/foo', params);
991
+ ```
992
+
993
+ ### Query string (Older browsers)
994
+
995
+ 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).
996
+
997
+ Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
998
+
999
+ ```js
1000
+ const qs = require('qs');
1001
+ axios.post('/foo', qs.stringify({ 'bar': 123 }));
1002
+ ```
1003
+
1004
+ Or in another way (ES6),
1005
+
1006
+ ```js
1007
+ import qs from 'qs';
1008
+ const data = { 'bar': 123 };
1009
+ const options = {
1010
+ method: 'POST',
1011
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
1012
+ data: qs.stringify(data),
1013
+ url,
1014
+ };
1015
+ axios(options);
1016
+ ```
1017
+
1018
+ ### Older Node.js versions
1019
+
1020
+ For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
1021
+
1022
+ ```js
1023
+ const querystring = require('querystring');
1024
+ axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
1025
+ ```
1026
+
1027
+ You can also use the [`qs`](https://github.com/ljharb/qs) library.
1028
+
1029
+ > **Note**: 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.
1030
+
1031
+ ### 🆕 Automatic serialization to URLSearchParams
1032
+
1033
+ Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
1034
+
1035
+ ```js
1036
+ const data = {
1037
+ x: 1,
1038
+ arr: [1, 2, 3],
1039
+ arr2: [1, [2], 3],
1040
+ users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
1041
+ };
1042
+
1043
+ await axios.postForm('https://postman-echo.com/post', data,
1044
+ {headers: {'content-type': 'application/x-www-form-urlencoded'}}
1045
+ );
1046
+ ```
1047
+
1048
+ The server will handle it as:
1049
+
1050
+ ```js
1051
+ {
1052
+ x: '1',
1053
+ 'arr[]': [ '1', '2', '3' ],
1054
+ 'arr2[0]': '1',
1055
+ 'arr2[1][0]': '2',
1056
+ 'arr2[2]': '3',
1057
+ 'arr3[]': [ '1', '2', '3' ],
1058
+ 'users[0][name]': 'Peter',
1059
+ 'users[0][surname]': 'griffin',
1060
+ 'users[1][name]': 'Thomas',
1061
+ 'users[1][surname]': 'Anderson'
1062
+ }
1063
+ ````
1064
+
1065
+ 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
1066
+
1067
+ ```js
1068
+ var app = express();
1069
+
1070
+ app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
1071
+
1072
+ app.post('/', function (req, res, next) {
1073
+ // echo body as JSON
1074
+ res.send(JSON.stringify(req.body));
1075
+ });
1076
+
1077
+ server = app.listen(3000);
1078
+ ```
1079
+
1080
+ ## Using `multipart/form-data` format
1081
+
1082
+ ### FormData
1083
+
1084
+ To send the data as a `multipart/formdata` you need to pass a formData instance as a payload.
1085
+ Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.
1086
+
1087
+ ```js
1088
+ const formData = new FormData();
1089
+ formData.append('foo', 'bar');
1090
+
1091
+ axios.post('https://httpbin.org/post', formData);
1092
+ ```
1093
+
1094
+ In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
1095
+
1096
+ ```js
1097
+ const FormData = require('form-data');
1098
+
1099
+ const form = new FormData();
1100
+ form.append('my_field', 'my value');
1101
+ form.append('my_buffer', new Buffer(10));
1102
+ form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
1103
+
1104
+ axios.post('https://example.com', form)
1105
+ ```
1106
+
1107
+ ### 🆕 Automatic serialization to FormData
1108
+
1109
+ Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
1110
+ header is set to `multipart/form-data`.
1111
+
1112
+ The following request will submit the data in a FormData format (Browser & Node.js):
1113
+
1114
+ ```js
1115
+ import axios from 'axios';
1116
+
1117
+ axios.post('https://httpbin.org/post', {x: 1}, {
1118
+ headers: {
1119
+ 'Content-Type': 'multipart/form-data'
1120
+ }
1121
+ }).then(({data}) => console.log(data));
1122
+ ```
1123
+
1124
+ In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
1125
+
1126
+ You can overload the FormData class by setting the `env.FormData` config variable,
1127
+ but you probably won't need it in most cases:
1128
+
1129
+ ```js
1130
+ const axios = require('axios');
1131
+ var FormData = require('form-data');
1132
+
1133
+ axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
1134
+ headers: {
1135
+ 'Content-Type': 'multipart/form-data'
1136
+ }
1137
+ }).then(({data}) => console.log(data));
1138
+ ```
1139
+
1140
+ Axios FormData serializer supports some special endings to perform the following operations:
1141
+
1142
+ - `{}` - serialize the value with JSON.stringify
1143
+ - `[]` - unwrap the array-like object as separate fields with the same key
1144
+
1145
+ > **Note**: unwrap/expand operation will be used by default on arrays and FileList objects
1146
+
1147
+ FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
1148
+
1149
+ - `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object
1150
+ to a `FormData` object by following custom rules.
1151
+
1152
+ - `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
1153
+
1154
+ - `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
1155
+ The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.
1156
+
1157
+ - `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects.
1158
+
1159
+ - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
1160
+ - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
1161
+ - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
1162
+
1163
+ Let's say we have an object like this one:
1164
+
1165
+ ```js
1166
+ const obj = {
1167
+ x: 1,
1168
+ arr: [1, 2, 3],
1169
+ arr2: [1, [2], 3],
1170
+ users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
1171
+ 'obj2{}': [{x:1}]
1172
+ };
1173
+ ```
1174
+
1175
+ The following steps will be executed by the Axios serializer internally:
1176
+
1177
+ ```js
1178
+ const formData = new FormData();
1179
+ formData.append('x', '1');
1180
+ formData.append('arr[]', '1');
1181
+ formData.append('arr[]', '2');
1182
+ formData.append('arr[]', '3');
1183
+ formData.append('arr2[0]', '1');
1184
+ formData.append('arr2[1][0]', '2');
1185
+ formData.append('arr2[2]', '3');
1186
+ formData.append('users[0][name]', 'Peter');
1187
+ formData.append('users[0][surname]', 'Griffin');
1188
+ formData.append('users[1][name]', 'Thomas');
1189
+ formData.append('users[1][surname]', 'Anderson');
1190
+ formData.append('obj2{}', '[{"x":1}]');
1191
+ ```
1192
+
1193
+ Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
1194
+ which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.
1195
+
1196
+ ## Files Posting
1197
+
1198
+ You can easily submit a single file:
1199
+
1200
+ ```js
1201
+ await axios.postForm('https://httpbin.org/post', {
1202
+ 'myVar' : 'foo',
1203
+ 'file': document.querySelector('#fileInput').files[0]
1204
+ });
1205
+ ```
1206
+
1207
+ or multiple files as `multipart/form-data`:
1208
+
1209
+ ```js
1210
+ await axios.postForm('https://httpbin.org/post', {
1211
+ 'files[]': document.querySelector('#fileInput').files
1212
+ });
1213
+ ```
1214
+
1215
+ `FileList` object can be passed directly:
1216
+
1217
+ ```js
1218
+ await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
1219
+ ```
1220
+
1221
+ All files will be sent with the same field names: `files[]`.
1222
+
1223
+ ## 🆕 HTML Form Posting (browser)
1224
+
1225
+ Pass HTML Form element as a payload to submit it as `multipart/form-data` content.
1226
+
1227
+ ```js
1228
+ await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
1229
+ ```
1230
+
1231
+ `FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
1232
+
1233
+ ```js
1234
+ await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
1235
+ headers: {
1236
+ 'Content-Type': 'application/json'
1237
+ }
1238
+ })
1239
+ ```
1240
+
1241
+ For example, the Form
1242
+
1243
+ ```html
1244
+ <form id="form">
1245
+ <input type="text" name="foo" value="1">
1246
+ <input type="text" name="deep.prop" value="2">
1247
+ <input type="text" name="deep prop spaced" value="3">
1248
+ <input type="text" name="baz" value="4">
1249
+ <input type="text" name="baz" value="5">
1250
+
1251
+ <select name="user.age">
1252
+ <option value="value1">Value 1</option>
1253
+ <option value="value2" selected>Value 2</option>
1254
+ <option value="value3">Value 3</option>
1255
+ </select>
1256
+
1257
+ <input type="submit" value="Save">
1258
+ </form>
1259
+ ```
1260
+
1261
+ will be submitted as the following JSON object:
1262
+
1263
+ ```js
1264
+ {
1265
+ "foo": "1",
1266
+ "deep": {
1267
+ "prop": {
1268
+ "spaced": "3"
1269
+ }
1270
+ },
1271
+ "baz": [
1272
+ "4",
1273
+ "5"
1274
+ ],
1275
+ "user": {
1276
+ "age": "value2"
1277
+ }
1278
+ }
1279
+ ````
1280
+
1281
+ Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.
1282
+
1283
+ ## 🆕 Progress capturing
1284
+
1285
+ Axios supports both browser and node environments to capture request upload/download progress.
1286
+ The frequency of progress events is forced to be limited to `3` times per second.
1287
+
1288
+ ```js
1289
+ await axios.post(url, data, {
1290
+ onUploadProgress: function (axiosProgressEvent) {
1291
+ /*{
1292
+ loaded: number;
1293
+ total?: number;
1294
+ progress?: number; // in range [0..1]
1295
+ bytes: number; // how many bytes have been transferred since the last trigger (delta)
1296
+ estimated?: number; // estimated time in seconds
1297
+ rate?: number; // upload speed in bytes
1298
+ upload: true; // upload sign
1299
+ }*/
1300
+ },
1301
+
1302
+ onDownloadProgress: function (axiosProgressEvent) {
1303
+ /*{
1304
+ loaded: number;
1305
+ total?: number;
1306
+ progress?: number;
1307
+ bytes: number;
1308
+ estimated?: number;
1309
+ rate?: number; // download speed in bytes
1310
+ download: true; // download sign
1311
+ }*/
1312
+ }
1313
+ });
1314
+ ```
1315
+
1316
+ You can also track stream upload/download progress in node.js:
1317
+
1318
+ ```js
1319
+ const {data} = await axios.post(SERVER_URL, readableStream, {
1320
+ onUploadProgress: ({progress}) => {
1321
+ console.log((progress * 100).toFixed(2));
1322
+ },
1323
+
1324
+ headers: {
1325
+ 'Content-Length': contentLength
1326
+ },
1327
+
1328
+ maxRedirects: 0 // avoid buffering the entire stream
1329
+ });
1330
+ ````
1331
+
1332
+ > **Note:**
1333
+ > Capturing FormData upload progress is not currently supported in node.js environments.
1334
+
1335
+ > **⚠️ Warning**
1336
+ > It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the **node.js** environment,
1337
+ > as follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm.
1338
+
1339
+
1340
+ ## 🆕 Rate limiting
1341
+
1342
+ Download and upload rate limits can only be set for the http adapter (node.js):
1343
+
1344
+ ```js
1345
+ const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, {
1346
+ onUploadProgress: ({progress, rate}) => {
1347
+ console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`)
1348
+ },
1349
+
1350
+ maxRate: [100 * 1024], // 100KB/s limit
1351
+ });
1352
+ ```
1353
+
1354
+ ## 🆕 AxiosHeaders
1355
+
1356
+ Axios has its own `AxiosHeaders` class to manipulate headers using a Map-like API that guarantees caseless work.
1357
+ Although HTTP is case-insensitive in headers, Axios will retain the case of the original header for stylistic reasons
1358
+ and for a workaround when servers mistakenly consider the header's case.
1359
+ The old approach of directly manipulating headers object is still available, but deprecated and not recommended for future usage.
1360
+
1361
+ ### Working with headers
1362
+
1363
+ An AxiosHeaders object instance can contain different types of internal values. that control setting and merging logic.
1364
+ The final headers object with string values is obtained by Axios by calling the `toJSON` method.
1365
+
1366
+ > Note: By JSON here we mean an object consisting only of string values intended to be sent over the network.
1367
+
1368
+ The header value can be one of the following types:
1369
+ - `string` - normal string value that will be sent to the server
1370
+ - `null` - skip header when rendering to JSON
1371
+ - `false` - skip header when rendering to JSON, additionally indicates that `set` method must be called with `rewrite` option set to `true`
1372
+ to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`)
1373
+ - `undefined` - value is not set
1374
+
1375
+ > Note: The header value is considered set if it is not equal to undefined.
1376
+
1377
+ The headers object is always initialized inside interceptors and transformers:
1378
+
1379
+ ```ts
1380
+ axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
1381
+ request.headers.set('My-header', 'value');
1382
+
1383
+ request.headers.set({
1384
+ "My-set-header1": "my-set-value1",
1385
+ "My-set-header2": "my-set-value2"
1386
+ });
1387
+
1388
+ request.headers.set('User-Agent', false); // disable subsequent setting the header by Axios
1389
+
1390
+ request.headers.setContentType('text/plain');
1391
+
1392
+ request.headers['My-set-header2'] = 'newValue' // direct access is deprecated
1393
+
1394
+ return request;
1395
+ }
1396
+ );
1397
+ ````
1398
+
1399
+ You can iterate over an `AxiosHeaders` instance using a `for...of` statement:
1400
+
1401
+ ````js
1402
+ const headers = new AxiosHeaders({
1403
+ foo: '1',
1404
+ bar: '2',
1405
+ baz: '3'
1406
+ });
1407
+
1408
+ for(const [header, value] of headers) {
1409
+ console.log(header, value);
1410
+ }
1411
+
1412
+ // foo 1
1413
+ // bar 2
1414
+ // baz 3
1415
+ ````
1416
+
1417
+ ### new AxiosHeaders(headers?)
1418
+
1419
+ Constructs a new `AxiosHeaders` instance.
1420
+
1421
+ ```
1422
+ constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
1423
+ ```
1424
+
1425
+ If the headers object is a string, it will be parsed as RAW HTTP headers.
1426
+
1427
+ ````js
1428
+ const headers = new AxiosHeaders(`
1429
+ Host: www.bing.com
1430
+ User-Agent: curl/7.54.0
1431
+ Accept: */*`);
1432
+
1433
+ console.log(headers);
1434
+
1435
+ // Object [AxiosHeaders] {
1436
+ // host: 'www.bing.com',
1437
+ // 'user-agent': 'curl/7.54.0',
1438
+ // accept: '*/*'
1439
+ // }
1440
+ ````
1441
+
1442
+ ### AxiosHeaders#set
1443
+
1444
+ ```ts
1445
+ set(headerName, value: Axios, rewrite?: boolean);
1446
+ set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean);
1447
+ set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean);
1448
+ ```
1449
+
1450
+ The `rewrite` argument controls the overwriting behavior:
1451
+ - `false` - do not overwrite if header's value is set (is not `undefined`)
1452
+ - `undefined` (default) - overwrite the header unless its value is set to `false`
1453
+ - `true` - rewrite anyway
1454
+
1455
+ The option can also accept a user-defined function that determines whether the value should be overwritten or not.
1456
+
1457
+ Returns `this`.
1458
+
1459
+ ### AxiosHeaders#get(header)
1460
+
1461
+ ```
1462
+ get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
1463
+ get(headerName: string, parser: RegExp): RegExpExecArray | null;
1464
+ ````
1465
+
1466
+ Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`,
1467
+ matcher function or internal key-value parser.
1468
+
1469
+ ```ts
1470
+ const headers = new AxiosHeaders({
1471
+ 'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h'
1472
+ });
1473
+
1474
+ console.log(headers.get('Content-Type'));
1475
+ // multipart/form-data; boundary=Asrf456BGe4h
1476
+
1477
+ console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters:
1478
+ // [Object: null prototype] {
1479
+ // 'multipart/form-data': undefined,
1480
+ // boundary: 'Asrf456BGe4h'
1481
+ // }
1482
+
1483
+
1484
+ console.log(headers.get('Content-Type', (value, name, headers) => {
1485
+ return String(value).replace(/a/g, 'ZZZ');
1486
+ }));
1487
+ // multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h
1488
+
1489
+ console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]);
1490
+ // boundary=Asrf456BGe4h
1491
+
1492
+ ```
1493
+
1494
+ Returns the value of the header.
1495
+
1496
+ ### AxiosHeaders#has(header, matcher?)
1497
+
1498
+ ```
1499
+ has(header: string, matcher?: AxiosHeaderMatcher): boolean;
1500
+ ```
1501
+
1502
+ Returns `true` if the header is set (has no `undefined` value).
1503
+
1504
+ ### AxiosHeaders#delete(header, matcher?)
1505
+
1506
+ ```
1507
+ delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
1508
+ ```
1509
+
1510
+ Returns `true` if at least one header has been removed.
1511
+
1512
+ ### AxiosHeaders#clear(matcher?)
1513
+
1514
+ ```
1515
+ clear(matcher?: AxiosHeaderMatcher): boolean;
1516
+ ```
1517
+
1518
+ Removes all headers.
1519
+ Unlike the `delete` method matcher, this optional matcher will be used to match against the header name rather than the value.
1520
+
1521
+ ```ts
1522
+ const headers = new AxiosHeaders({
1523
+ 'foo': '1',
1524
+ 'x-foo': '2',
1525
+ 'x-bar': '3',
1526
+ });
1527
+
1528
+ console.log(headers.clear(/^x-/)); // true
1529
+
1530
+ console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' }
1531
+ ```
1532
+
1533
+ Returns `true` if at least one header has been cleared.
1534
+
1535
+ ### AxiosHeaders#normalize(format);
1536
+
1537
+ If the headers object was changed directly, it can have duplicates with the same name but in different cases.
1538
+ This method normalizes the headers object by combining duplicate keys into one.
1539
+ Axios uses this method internally after calling each interceptor.
1540
+ Set `format` to true for converting headers name to lowercase and capitalize the initial letters (`cOntEnt-type` => `Content-Type`)
1541
+
1542
+ ```js
1543
+ const headers = new AxiosHeaders({
1544
+ 'foo': '1',
1545
+ });
1546
+
1547
+ headers.Foo = '2';
1548
+ headers.FOO = '3';
1549
+
1550
+ console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' }
1551
+ console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' }
1552
+ console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' }
1553
+ ```
1554
+
1555
+ Returns `this`.
1556
+
1557
+ ### AxiosHeaders#concat(...targets)
1558
+
1559
+ ```
1560
+ concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
1561
+ ```
1562
+
1563
+ Merges the instance with targets into a new `AxiosHeaders` instance. If the target is a string, it will be parsed as RAW HTTP headers.
1564
+
1565
+ Returns a new `AxiosHeaders` instance.
1566
+
1567
+ ### AxiosHeaders#toJSON(asStrings?)
1568
+
1569
+ ````
1570
+ toJSON(asStrings?: boolean): RawAxiosHeaders;
1571
+ ````
1572
+
1573
+ Resolve all internal headers values into a new null prototype object.
1574
+ Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas.
1575
+
1576
+ ### AxiosHeaders.from(thing?)
1577
+
1578
+ ````
1579
+ from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
1580
+ ````
1581
+
1582
+ Returns a new `AxiosHeaders` instance created from the raw headers passed in,
1583
+ or simply returns the given headers object if it's an `AxiosHeaders` instance.
1584
+
1585
+ ### AxiosHeaders.concat(...targets)
1586
+
1587
+ ````
1588
+ concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
1589
+ ````
1590
+
1591
+ Returns a new `AxiosHeaders` instance created by merging the target objects.
1592
+
1593
+ ### Shortcuts
1594
+
1595
+ The following shortcuts are available:
1596
+
1597
+ - `setContentType`, `getContentType`, `hasContentType`
1598
+
1599
+ - `setContentLength`, `getContentLength`, `hasContentLength`
1600
+
1601
+ - `setAccept`, `getAccept`, `hasAccept`
1602
+
1603
+ - `setUserAgent`, `getUserAgent`, `hasUserAgent`
1604
+
1605
+ - `setContentEncoding`, `getContentEncoding`, `hasContentEncoding`
1606
+
1607
+ ## 🔥 Fetch adapter
1608
+
1609
+ Fetch adapter was introduced in `v1.7.0`. By default, it will be used if `xhr` and `http` adapters are not available in the build,
1610
+ or not supported by the environment.
1611
+ To use it by default, it must be selected explicitly:
1612
+
1613
+ ```js
1614
+ const {data} = axios.get(url, {
1615
+ adapter: 'fetch' // by default ['xhr', 'http', 'fetch']
1616
+ })
1617
+ ```
1618
+
1619
+ You can create a separate instance for this:
1620
+
1621
+ ```js
1622
+ const fetchAxios = axios.create({
1623
+ adapter: 'fetch'
1624
+ });
1625
+
1626
+ const {data} = fetchAxios.get(url);
1627
+ ```
1628
+
1629
+ The adapter supports the same functionality as `xhr` adapter, **including upload and download progress capturing**.
1630
+ Also, it supports additional response types such as `stream` and `formdata` (if supported by the environment).
1631
+
1632
+ ### 🔥 Custom fetch
1633
+
1634
+ Starting from `v1.12.0`, you can customize the fetch adapter to use a custom fetch API instead of environment globals.
1635
+ You can pass a custom `fetch` function, `Request`, and `Response` constructors via env config.
1636
+ This can be helpful in case of custom environments & app frameworks.
1637
+
1638
+ Also, when using a custom fetch, you may need to set custom Request and Response too. If you don't set them, global objects will be used.
1639
+ If your custom fetch api does not have these objects, and the globals are incompatible with a custom fetch,
1640
+ you must disable their use inside the fetch adapter by passing null.
1641
+
1642
+ > Note: Setting `Request` & `Response` to `null` will make it impossible for the fetch adapter to capture the upload & download progress.
1643
+
1644
+ Basic example:
1645
+
1646
+ ```js
1647
+ import customFetchFunction from 'customFetchModule';
1648
+
1649
+ const instance = axios.create({
1650
+ adapter: 'fetch',
1651
+ onDownloadProgress(e) {
1652
+ console.log('downloadProgress', e);
1653
+ },
1654
+ env: {
1655
+ fetch: customFetchFunction,
1656
+ Request: null, // undefined -> use the global constructor
1657
+ Response: null
1658
+ }
1659
+ });
1660
+ ```
1661
+
1662
+ #### 🔥 Using with Tauri
1663
+
1664
+ A minimal example of setting up Axios for use in a [Tauri](https://tauri.app/plugin/http-client/) app with a platform fetch function that ignores CORS policy for requests.
1665
+
1666
+ ```js
1667
+ import { fetch } from "@tauri-apps/plugin-http";
1668
+ import axios from "axios";
1669
+
1670
+ const instance = axios.create({
1671
+ adapter: 'fetch',
1672
+ onDownloadProgress(e) {
1673
+ console.log('downloadProgress', e);
1674
+ },
1675
+ env: {
1676
+ fetch
1677
+ }
1678
+ });
1679
+
1680
+ const {data} = await instance.get("https://google.com");
1681
+ ```
1682
+
1683
+ #### 🔥 Using with SvelteKit
1684
+
1685
+ [SvelteKit](https://svelte.dev/docs/kit/web-standards#Fetch-APIs) framework has a custom implementation of the fetch function for server rendering (so called `load` functions), and also uses relative paths,
1686
+ which makes it incompatible with the standard URL API. So, Axios must be configured to use the custom fetch API:
1687
+
1688
+ ```js
1689
+ export async function load({ fetch }) {
1690
+ const {data: post} = await axios.get('https://jsonplaceholder.typicode.com/posts/1', {
1691
+ adapter: 'fetch',
1692
+ env: {
1693
+ fetch,
1694
+ Request: null,
1695
+ Response: null
1696
+ }
1697
+ });
1698
+
1699
+ return { post };
1700
+ }
1701
+ ```
1702
+
1703
+ ## 🔥 HTTP2
1704
+
1705
+ In version `1.13.0`, experimental `HTTP2` support was added to the `http` adapter.
1706
+ The `httpVersion` option is now available to select the protocol version used.
1707
+ Additional native options for the internal `session.request()` call can be passed via the `http2Options` config.
1708
+ This config also includes the custom `sessionTimeout` parameter, which defaults to `1000ms`.
1709
+
1710
+ ```js
1711
+ const form = new FormData();
1712
+
1713
+ form.append('foo', '123');
1714
+
1715
+ const {data, headers, status} = await axios.post('https://httpbin.org/post', form, {
1716
+ httpVersion: 2,
1717
+ http2Options: {
1718
+ // rejectUnauthorized: false,
1719
+ // sessionTimeout: 1000
1720
+ },
1721
+ onUploadProgress(e) {
1722
+ console.log('upload progress', e);
1723
+ },
1724
+ onDownloadProgress(e) {
1725
+ console.log('download progress', e);
1726
+ },
1727
+ responseType: 'arraybuffer'
1728
+ });
1729
+ ```
1730
+
1731
+ ## Semver
1732
+
1733
+ Since Axios has reached a `v.1.0.0` we will fully embrace semver as per the spec [here](https://semver.org/)
1734
+
1735
+ ## Promises
1736
+
1737
+ axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises).
1738
+ If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
1739
+
1740
+ ## TypeScript
1741
+
1742
+ axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors.
1743
+
1744
+ ```typescript
1745
+ let user: User = null;
1746
+ try {
1747
+ const { data } = await axios.get('/user?ID=12345');
1748
+ user = data.userDetails;
1749
+ } catch (error) {
1750
+ if (axios.isAxiosError(error)) {
1751
+ handleAxiosError(error);
1752
+ } else {
1753
+ handleUnexpectedError(error);
1754
+ }
1755
+ }
1756
+ ```
1757
+
1758
+ Because axios dual publishes with an ESM default export and a CJS `module.exports`, there are some caveats.
1759
+ The recommended setting is to use `"moduleResolution": "node16"` (this is implied by `"module": "node16"`). Note that this requires TypeScript 4.7 or greater.
1760
+ If use ESM, your settings should be fine.
1761
+ If you compile TypeScript to CJS and you can’t use `"moduleResolution": "node 16"`, you have to enable `esModuleInterop`.
1762
+ If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`.
1763
+
1764
+ ## Online one-click setup
1765
+
1766
+ You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online.
1767
+
1768
+ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js)
1769
+
1770
+
1771
+ ## Resources
1772
+
1773
+ * [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
1774
+ * [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
1775
+ * [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
1776
+ * [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md)
1777
+
1778
+ ## Credits
1779
+
1780
+ 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.
1781
+
1782
+ ## License
1783
+
1784
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)