市场夺宝奇兵
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.

1756 lines
72 KiB

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