You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1657 lines
61 KiB

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