source: frontend/node_modules/axios/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 90.3 KB
RevLineΒ 
[9af201e]1<h3 align="center">πŸ’Ž Platinum sponsors <br /></h3>
2<table align="center">
3 <tr>
4 <td align="center" width="50%">
5 <a
6 href="https://thanks.dev/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
7 style="padding: 10px; display: inline-block"
8 target="_blank"
9 >
10 <img
11 width="90px"
12 height="90px"
13 src="https://images.opencollective.com/thanks-dev/360b917/logo/256.png?height=256"
14 alt="Thanks.dev"
15 />
16 </a>
17 <p
18 align="center"
19 >
20 We're passionate about making open source sustainable. Scan your dependency tree to better understand which open source projects need funding.
21 </p>
22 <p align="center">
23 <a
24 href="https://thanks.dev/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
25 target="_blank"
26 ><b>thanks.dev</b></a
27 >
28 </p>
29 </td>
30 <td align="center" width="50%">
31 <a
32 href="https://hopper.security/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
33 style="padding: 10px; display: inline-block"
34 target="_blank"
35 >
36 <img
37 width="90px"
38 height="90px"
39 src="https://images.opencollective.com/hopper-security/c4f7de2/avatar.png"
40 alt="Hopper Security"
41 />
42 </a>
43 <p align="center">
44 Hopper provides a secure, open-source registry where every component is verified against malware and continuously remediated for vulnerabilities across all versions. In simple terms, Hopper removes the need to manage software supply chain risk altogether.
45 </p>
46 <p align="center">
47 <a
48 href="https://hopper.security/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
49 target="_blank"
50 ><b>hopper.security</b></a
51 >
52 </p>
53 </td>
54 </tr>
55</table>
56<table align="center">
57 <tr>
58 <td align="center" width="50%">
59 <a
60 href="https://opencollective.com/axios/contribute"
61 target="_blank"
62 >πŸ’œ Become a sponsor</a
63 >
64 </td>
65 <td align="center" width="50%">
66 <a
67 href="https://opencollective.com/axios/contribute"
68 target="_blank"
69 >πŸ’œ Become a sponsor</a
70 >
71 </td>
72 </tr>
73</table>
74<h3 align="center">πŸ₯‡ Gold sponsors <br /></h3>
75<table align="center" width="100%">
76 <tr width="33.333333333333336%">
77 <td align="center" width="33.333333333333336%">
78 <a
79 href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
80 style="padding: 10px; display: inline-block"
81 target="_blank"
82 >
83 <img
84 width="90px"
85 height="90px"
86 src="https://images.opencollective.com/principal/431e690/logo.png"
87 alt="Principal Financial Group"
88 />
89 </a>
90 <p
91 align="center"
92 >
93 Free tools to help with your financial planning needs!
94 </p>
95 <p align="center">
96 <a
97 href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
98 target="_blank"
99 ><b>principal.com</b></a
100 >
101 </p>
102 </td>
103 <td align="center" width="33.333333333333336%">
104 <a
105 href="https://opensource.sap.com?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
106 style="padding: 10px; display: inline-block"
107 target="_blank"
108 >
109 <img
110 width="90px"
111 height="90px"
112 src="https://avatars.githubusercontent.com/u/2531208?s=200&v=4"
113 alt="SAP"
114 />
115 </a>
116 <p
117 align="center"
118 title="SAP SE, a global software company, is one of the largest vendors of ERP and other enterprise applications."
119 >
120 BSAP SE, a global software company, is one of the largest vendors of ERP and other enterprise applications.
121 </p>
122 <p align="center">
123 <a
124 href="https://opensource.sap.com?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
125 target="_blank"
126 ><b>opensource.sap.com</b></a
127 >
128 </p>
129 </td>
130 <td align="center" width="33.333333333333336%">
131 <a
132 href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship"
133 style="padding: 10px; display: inline-block"
134 target="_blank"
135 >
136 <img
137 width="90px"
138 height="90px"
139 src="https://images.opencollective.com/descope/b53243e/logo.png"
140 alt="Descope"
141 />
142 </a>
143 <p
144 align="center"
145 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."
146 >
147 Reduce user friction, prevent account takeover, and get a 360Β° view of your customer and agentic identities with the Descope External IAM platform.
148 </p>
149 <p align="center">
150 <a
151 href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship"
152 target="_blank"
153 ><b>descope.com</b></a
154 >
155 </p>
156 </td>
157 </tr>
158 <tr width="33.333333333333336%">
159 <td align="center" width="33.333333333333336%">
160 <a
161 href="https://stytch.com/"
162 style="padding: 10px; display: inline-block"
163 target="_blank"
164 >
165 <img
166 width="90px"
167 height="90px"
168 src="https://images.opencollective.com/stytch/f84ce43/logo/256.png?height=256"
169 alt="Stytch"
170 />
171 </a>
172 <p
173 align="center"
174 >
175 The identity platform for humans & AI agents
176 </p>
177 <p align="center">
178 <a
179 href="https://stytch.com"
180 target="_blank"
181 ><b>stytch.com</b></a
182 >
183 </p>
184 </td>
185 <td align="center" width="33.333333333333336%">
186 <a
187 href="https://rxdb.info/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship&utm_content=logo"
188 style="padding: 10px; display: inline-block"
189 target="_blank"
190 >
191 <img
192 width="90px"
193 height="90px"
194 src="https://rxdb.info/files/logo/logo_text_white.svg"
195 alt="RxDB"
196 />
197 </a>
198 <p
199 align="center"
200 >
201 RxDB is a NoSQL database for JavaScript that runs directly in your app.
202 </p>
203 <p align="center">
204 <a
205 href="https://rxdb.info/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship&utm_content=logo"
206 target="_blank"
207 ><b>rxdb.info</b></a
208 >
209 </p>
210 </td>
211 <td align="center" width="33.333333333333336%">
212 <a
213 href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
214 style="padding: 10px; display: inline-block"
215 target="_blank"
216 >
217 <img
218 width="70px"
219 height="70px"
220 src="https://images.opencollective.com/instagram-likes/2a72a03/avatar.png"
221 alt="Poprey"
222 />
223 </a>
224 <p align="center">
225 Buy Instagram Likes
226 </p>
227 <p align="center">
228 <a
229 href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
230 target="_blank"
231 ><b>poprey.com</b></a
232 >
233 </p>
234 </td>
235 </tr>
236 <tr width="33.333333333333336%">
237 <td align="center" width="33.333333333333336%">
238 <a
239 href="https://buzzoid.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
240 style="padding: 10px; display: inline-block"
241 target="_blank"
242 >
243 <img
244 width="71px"
245 height="70px"
246 src="https://images.opencollective.com/buzzoid-buy-instagram-followers/56a09fe/logo.png"
247 alt="Buzzoid - Buy Instagram Followers"
248 />
249 </a>
250 <p
251 align="center"
252 >
253 At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rated world&#39;s #1 IG service since 2012.
254 </p>
255 <p align="center">
256 <a
257 href="https://buzzoid.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
258 target="_blank"
259 ><b>buzzoid.com</b></a
260 >
261 </p>
262 </td>
263 <td align="center" width="33.333333333333336%">
264 <a
265 href="https://twicsy.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
266 style="padding: 10px; display: inline-block"
267 target="_blank"
268 >
269 <img
270 width="71px"
271 height="70px"
272 src="https://images.opencollective.com/buy-instagram-followers-twicsy/b4c5d7f/logo/256.png?height=256"
273 alt="Buy Instagram Followers Twicsy"
274 />
275 </a>
276 <p
277 align="center"
278 >
279 Buy real Instagram followers from Twicsy. Twicsy has been voted the best site to buy followers from the likes of US Magazine.
280 </p>
281 <p align="center">
282 <a
283 href="https://twicsy.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
284 target="_blank"
285 ><b>twicsy.com</b></a
286 >
287 </p>
288 </td>
289 <td align="center" width="33.333333333333336%">
290 <a
291 href="https://opencollective.com/axios/contribute"
292 target="_blank"
293 >πŸ’œ Become a sponsor</a
294 >
295 </td>
296 </tr>
297</table>
298
299
300<!--<div>marker</div>-->
301
302<br><br>
303
304<div align="center">
305 <a href="https://axios.rest"><img src="https://axios.rest/logo.svg" alt="Axios" /></a><br>
306</div>
307
308<p align="center">Promise based HTTP client for the browser and node.js</p>
309
310<p align="center">
311 <a href="https://axios.rest/"><b>Website</b></a> β€’
312 <a href="https://axios.rest/pages/getting-started/first-steps.html"><b>Documentation</b></a>
313</p>
314
315<div align="center">
316
317[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
318[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
319[![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)
320[![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)
321[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
322[![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)
323[![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest)
324[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios)
325[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
326[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
327[![Contributors](https://img.shields.io/github/contributors/axios/axios.svg?style=flat-square)](CONTRIBUTORS.md)
328
329</div>
330
331## Table of Contents
332
333- [Features](#features)
334- [Browser Support](#browser-support)
335- [Installing](#installing)
336 - [Package manager](#package-manager)
337 - [CDN](#cdn)
338- [Example](#example)
339- [Axios API](#axios-api)
340- [Request method aliases](#request-method-aliases)
341- [Concurrency πŸ‘Ž](#concurrency-deprecated)
342- [Creating an instance](#creating-an-instance)
343- [Instance methods](#instance-methods)
344- [Request Config](#request-config)
345- [Response Schema](#response-schema)
346- [Config Defaults](#config-defaults)
347 - [Global axios defaults](#global-axios-defaults)
348 - [Custom instance defaults](#custom-instance-defaults)
349 - [Config order of precedence](#config-order-of-precedence)
350- [Interceptors](#interceptors)
351 - [Multiple Interceptors](#multiple-interceptors)
352- [Handling Errors](#handling-errors)
353- [Handling Timeouts](#handling-timeouts)
354- [Cancellation](#cancellation)
355 - [AbortController](#abortcontroller)
356 - [CancelToken πŸ‘Ž](#canceltoken-deprecated)
357- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
358 - [URLSearchParams](#urlsearchparams)
359 - [Query string](#query-string-older-browsers)
360 - [πŸ†• Automatic serialization](#-automatic-serialization-to-urlsearchparams)
361- [Using multipart/form-data format](#using-multipartform-data-format)
362 - [FormData](#formdata)
363 - [πŸ†• Automatic serialization](#-automatic-serialization-to-formdata)
364- [Files Posting](#files-posting)
365- [HTML Form Posting](#-html-form-posting-browser)
366- [πŸ†• Progress capturing](#-progress-capturing)
367- [πŸ†• Rate limiting](#-rate-limiting)
368- [πŸ†• AxiosHeaders](#-axiosheaders)
369- [πŸ”₯ Fetch adapter](#-fetch-adapter)
370 - [πŸ”₯ Custom fetch](#-custom-fetch)
371 - [πŸ”₯ Using with Tauri](#-using-with-tauri)
372 - [πŸ”₯ Using with SvelteKit](#-using-with-sveltekit)
373- [πŸ”₯ HTTP2](#-http2)
374- [Semver](#semver)
375- [Promises](#promises)
376- [TypeScript](#typescript)
377- [Contributing](#contributing)
378 - [Local setup](#local-setup)
379- [Resources](#resources)
380- [Credits](#credits)
381- [License](#license)
382
383## Features
384
385- **Browser Requests:** Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) directly from the browser.
386- **Node.js Requests:** Make [http](https://nodejs.org/api/http.html) requests from Node.js environments.
387- **Promise-based:** Fully supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API for easier asynchronous code.
388- **Interceptors:** Intercept requests and responses to add custom logic or transform data.
389- **Data Transformation:** Transform request and response data automatically.
390- **Request Cancellation:** Cancel requests using built-in mechanisms.
391- **Automatic JSON Handling:** Automatically serializes and parses [JSON](https://www.json.org/json-en.html) data.
392- **Form Serialization:** πŸ†• Automatically serializes data objects to `multipart/form-data` or `x-www-form-urlencoded` formats.
393- **XSRF Protection:** Client-side support to protect against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery).
394
395## Browser Support
396
397| Chrome | Firefox | Safari | Opera | Edge |
398| :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------: |
399| ![Chrome browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) |
400| Latest βœ” | Latest βœ” | Latest βœ” | Latest βœ” | Latest βœ” |
401
402[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
403
404## Installing
405
406### Package manager
407
408Using npm:
409
410```bash
411$ npm install axios
412```
413
414Using yarn:
415
416```bash
417$ yarn add axios
418```
419
420Using pnpm:
421
422```bash
423$ pnpm add axios
424```
425
426Using bun:
427
428```bash
429$ bun add axios
430```
431
432Once the package is installed, you can import the library using `import` or `require` approach:
433
434```js
435import axios, { isCancel, AxiosError } from 'axios';
436```
437
438You can also use the default export, since the named export is just a re-export from the Axios factory:
439
440```js
441import axios from 'axios';
442
443console.log(axios.isCancel('something'));
444```
445
446If you use `require` for importing, **only the default export is available**:
447
448```js
449const axios = require('axios');
450
451console.log(axios.isCancel('something'));
452```
453
454For some bundlers and some ES6 linters you may need to do the following:
455
456```js
457import { default as axios } from 'axios';
458```
459
460For cases where something went wrong when trying to import a module into a custom or legacy environment,
461you can try importing the module package directly:
462
463```js
464const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
465// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
466```
467
468### CDN
469
470Using jsDelivr CDN (ES5 UMD browser module):
471
472```html
473<script src="https://cdn.jsdelivr.net/npm/axios@1.13.2/dist/axios.min.js"></script>
474```
475
476Using unpkg CDN:
477
478```html
479<script src="https://unpkg.com/axios@1.13.2/dist/axios.min.js"></script>
480```
481
482## Example
483
484```js
485import axios from 'axios';
486//const axios = require('axios'); // legacy way
487
488try {
489 const response = await axios.get('/user?ID=12345');
490 console.log(response);
491} catch (error) {
492 console.error(error);
493}
494
495// Optionally the request above could also be done as
496axios
497 .get('/user', {
498 params: {
499 ID: 12345,
500 },
501 timeout: 5000, // 5 seconds β€” see "Handling Timeouts" below for matching error handling
502 })
503 .then(function (response) {
504 console.log(response);
505 })
506 .catch(function (error) {
507 console.log(error);
508 })
509 .finally(function () {
510 // always executed
511 });
512
513// Want to use async/await? Add the `async` keyword to your outer function/method.
514async function getUser() {
515 try {
516// Example: GET request with query parameters
517const response = await axios.get('/user', {
518 params: {
519 ID: 12345
520 }
521});
522
523// Using the `params` option improves readability and automatically formats query strings
524
525console.log(response);
526 } catch (error) {
527 console.error(error);
528 }
529}
530```
531
532> **Note**: Set a `timeout` in production β€” without one, a stalled request can hang
533> indefinitely. See [Handling Timeouts](#handling-timeouts) for the matching error handling.
534
535> **Note**: `async/await` is part of ECMAScript 2017 and is not supported in Internet
536> Explorer and older browsers, so use with caution.
537
538Performing a `POST` request
539
540```js
541const response = await axios.post('/user', {
542 firstName: 'Fred',
543 lastName: 'Flintstone',
544});
545console.log(response);
546```
547
548Performing multiple concurrent requests
549
550```js
551function getUserAccount() {
552 return axios.get('/user/12345');
553}
554
555function getUserPermissions() {
556 return axios.get('/user/12345/permissions');
557}
558
559Promise.all([getUserAccount(), getUserPermissions()]).then(function (results) {
560 const acct = results[0];
561 const perm = results[1];
562});
563```
564
565## axios API
566
567Requests can be made by passing the relevant config to `axios`.
568
569##### axios(config)
570
571```js
572// Send a POST request
573axios({
574 method: 'post',
575 url: '/user/12345',
576 data: {
577 firstName: 'Fred',
578 lastName: 'Flintstone',
579 },
580});
581```
582
583```js
584// GET request for remote image in node.js
585const response = await axios({
586 method: 'get',
587 url: 'https://bit.ly/2mTM3nY',
588 responseType: 'stream',
589});
590response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'));
591```
592
593##### axios(url[, config])
594
595```js
596// Send a GET request (default method)
597axios('/user/12345');
598```
599
600### Request method aliases
601
602For convenience, aliases have been provided for all common request methods.
603
604##### axios.request(config)
605
606##### axios.get(url[, config])
607
608##### axios.delete(url[, config])
609
610##### axios.head(url[, config])
611
612##### axios.options(url[, config])
613
614##### axios.post(url[, data[, config]])
615
616##### axios.put(url[, data[, config]])
617
618##### axios.patch(url[, data[, config]])
619
620###### NOTE
621
622When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
623
624### Concurrency (Deprecated)
625
626Please use `Promise.all` to replace the below functions.
627
628Helper functions for dealing with concurrent requests.
629
630axios.all(iterable)
631axios.spread(callback)
632
633### Creating an instance
634
635You can create a new instance of axios with a custom config.
636
637##### axios.create([config])
638
639```js
640const instance = axios.create({
641 baseURL: 'https://some-domain.com/api/',
642 timeout: 1000,
643 headers: { 'X-Custom-Header': 'foobar' },
644});
645```
646
647### Instance methods
648
649The available instance methods are listed below. The specified config will be merged with the instance config.
650
651##### axios#request(config)
652
653##### axios#get(url[, config])
654
655##### axios#delete(url[, config])
656
657##### axios#head(url[, config])
658
659##### axios#options(url[, config])
660
661##### axios#post(url[, data[, config]])
662
663##### axios#put(url[, data[, config]])
664
665##### axios#patch(url[, data[, config]])
666
667##### axios#getUri([config])
668
669## Request Config
670
671### ⚠️ Security notice: decompression-bomb protection is opt-in
672
673By default `maxContentLength` and `maxBodyLength` are `-1` (unlimited). A malicious or compromised server can return a tiny gzip/deflate/brotli body that expands to gigabytes and exhaust the Node.js process.
674
675If you call servers you do not fully trust, **set a cap**:
676
677```js
678axios.defaults.maxContentLength = 10 * 1024 * 1024; // 10 MB
679axios.defaults.maxBodyLength = 10 * 1024 * 1024;
680```
681
682See the [security guide](https://axios.rest/pages/misc/security.html) for details.
683
684These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
685
686```js
687{
688 // `url` is the server URL that will be used for the request
689 url: '/user',
690
691 // `method` is the request method to be used when making the request
692 method: 'get', // default
693
694 // `baseURL` will be prepended to `url` unless `url` is absolute and the option `allowAbsoluteUrls` is set to true.
695 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
696 // to the methods of that instance.
697 baseURL: 'https://some-domain.com/api/',
698
699 // `allowAbsoluteUrls` determines whether or not absolute URLs will override a configured `baseUrl`.
700 // When set to true (default), absolute values for `url` will override `baseUrl`.
701 // When set to false, absolute values for `url` will always be prepended by `baseUrl`.
702 allowAbsoluteUrls: true,
703
704 // `transformRequest` allows changes to the request data before it is sent to the server
705 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
706 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
707 // FormData or Stream
708 // You may modify the headers object.
709 transformRequest: [function (data, headers) {
710 // Do whatever you want to transform the data
711
712 return data;
713 }],
714
715 // `transformResponse` allows changes to the response data to be made before
716 // it is passed to then/catch
717 transformResponse: [function (data) {
718 // Do whatever you want to transform the data
719
720 return data;
721 }],
722
723 // `parseReviver` is an optional function that will be passed as the
724 // second argument (reviver) to JSON.parse()
725 parseReviver: function (key, value, context) {
726 // In modern environments, context.source provides the raw JSON string
727 // allowing for precision-safe parsing of BigInt
728 if (typeof value === 'number' && context?.source) {
729 const isInteger = Number.isInteger(value);
730 const isUnsafe = !Number.isSafeInteger(value);
731 const isValidIntegerString = /^-?\d+$/.test(context.source);
732
733 if (isInteger && isUnsafe && isValidIntegerString) {
734 try {
735 return BigInt(context.source);
736 } catch {
737 // Fallback: return original value if parsing fails
738 }
739 }
740 }
741 return value;
742 },
743
744 // `headers` are custom headers to be sent
745 headers: {'X-Requested-With': 'XMLHttpRequest'},
746
747 // `params` are the URL parameters to be sent with the request
748 // Must be a plain object or a URLSearchParams object
749 params: {
750 ID: 12345
751 },
752
753 // `paramsSerializer` is an optional config that allows you to customize serializing `params`.
754 paramsSerializer: {
755
756 // Custom encoder function which sends key/value pairs in an iterative fashion.
757 encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },
758
759 // Custom serializer function for the entire parameter. Allows the user to mimic pre 1.x behaviour.
760 serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
761
762 // Configuration for formatting array indexes in the params.
763 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).
764
765 // Maximum object nesting depth when serializing params. Payloads deeper than this throw an
766 // AxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED. Default: 100. Set to Infinity to disable.
767 maxDepth: 100
768
769 },
770
771 // `data` is the data to be sent as the request body
772 // Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
773 // When no `transformRequest` is set, it must be of one of the following types:
774 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
775 // - Browser only: FormData, File, Blob
776 // - Node only: Stream, Buffer, FormData (form-data package)
777 data: {
778 firstName: 'Fred'
779 },
780
781 // `formDataHeaderPolicy` controls how node.js FormData#getHeaders() is copied.
782 // 'legacy' (default) copies all returned headers for v1 compatibility.
783 // 'content-only' copies only Content-Type and Content-Length.
784 formDataHeaderPolicy: 'legacy',
785
786 // syntax alternative to send data into the body
787 // method post
788 // only the value is sent, not the key
789 data: 'Country=Brasil&City=Belo Horizonte',
790
791 // `timeout` specifies the number of milliseconds before the request times out.
792 // If the request takes longer than `timeout`, the request will be aborted.
793 timeout: 1000, // default is `0` (no timeout)
794
795 // `withCredentials` indicates whether or not cross-site Access-Control requests
796 // should be made using credentials
797 // This only controls whether the browser sends credentials.
798 // It does not control whether the XSRF header is added.
799 withCredentials: false, // default
800
801 // `adapter` allows custom handling of requests which makes testing easier.
802 // Return a promise and supply a valid response (see lib/adapters/README.md)
803 adapter: function (config) {
804 /* ... */
805 },
806 // Also, you can set the name of the built-in adapter, or provide an array with their names
807 // to choose the first available in the environment
808 adapter: 'xhr', // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
809
810 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
811 // This will set an `Authorization` header, overwriting any existing
812 // `Authorization` custom headers you have set using `headers`.
813 // Please note that only HTTP Basic auth is configurable through this parameter.
814 // For Bearer tokens and such, use `Authorization` custom headers instead.
815 auth: {
816 username: 'janedoe',
817 password: 's00pers3cret'
818 },
819
820 // `responseType` indicates the type of data that the server will respond with
821 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
822 // browser only: 'blob'
823 responseType: 'json', // default
824
825 // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
826 // Note: Ignored for `responseType` of 'stream' or client-side requests
827 // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
828 // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
829 // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
830 responseEncoding: 'utf8', // default
831
832 // `xsrfCookieName` is the name of the cookie to use as a value for the xsrf token
833 xsrfCookieName: 'XSRF-TOKEN', // default
834
835 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
836 xsrfHeaderName: 'X-XSRF-TOKEN', // default
837
838 // `withXSRFToken` defines whether to send the XSRF header in browser requests.
839 // `undefined` (default) - set XSRF header only for the same origin requests
840 // `true` - always set XSRF header, including for cross-origin requests
841 // `false` - never set XSRF header
842 // function - resolve with custom logic; receives the internal config object
843 withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),
844
845 // `withXSRFToken` controls whether Axios reads the XSRF cookie and sets the XSRF header.
846 // - `undefined` (default): the XSRF header is set only for same-origin requests.
847 // - `true`: attempt to set the XSRF header for all requests (including cross-origin).
848 // - `false`: never set the XSRF header.
849 // - function: a callback that receives the request `config` and returns `true`,
850 // `false`, or `undefined` to decide per-request behavior.
851 //
852 // Note about `withCredentials`: `withCredentials` controls whether cross-site
853 // requests include credentials (cookies and HTTP auth). In older Axios versions,
854 // setting `withCredentials: true` implicitly caused Axios to set the XSRF header
855 // for cross-origin requests. Newer Axios separates these concerns: to allow the
856 // XSRF header to be sent for cross-origin requests you should set both
857 // `withCredentials: true` and `withXSRFToken: true`.
858 //
859 // Example:
860 // axios.get('/user', { withCredentials: true, withXSRFToken: true });
861
862 // `onUploadProgress` allows handling of progress events for uploads
863 // browser & node.js
864 onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
865 // Do whatever you want with the Axios progress event
866 },
867
868 // `onDownloadProgress` allows handling of progress events for downloads
869 // browser & node.js
870 onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
871 // Do whatever you want with the Axios progress event
872 },
873
874 // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
875 maxContentLength: 2000,
876
877 // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
878 maxBodyLength: 2000,
879
880 // `redact` masks matching config keys when AxiosError#toJSON() is called.
881 // Matching is case-insensitive and recursive. It does not change the request.
882 redact: ['authorization', 'password'],
883
884 // `validateStatus` defines whether to resolve or reject the promise for a given
885 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
886 // or `undefined`), the promise will be resolved; otherwise, the promise will be
887 // rejected.
888 validateStatus: function (status) {
889 return status >= 200 && status < 300; // default
890 },
891
892 // `maxRedirects` defines the maximum number of redirects to follow in node.js.
893 // If set to 0, no redirects will be followed.
894 maxRedirects: 21, // default
895
896 // `beforeRedirect` defines a function that will be called before redirect.
897 // Use this to adjust the request options upon redirecting,
898 // to inspect the latest response headers,
899 // or to cancel the request by throwing an error
900 // If maxRedirects is set to 0, `beforeRedirect` is not used.
901
902 beforeRedirect: (options, { headers }) => {
903 if (
904 options.hostname === "example.com" &&
905 options.protocol === "https:"
906 ) {
907 options.auth = "user:password";
908 }
909 },
910 // Security note:
911 // The `beforeRedirect` hook runs after sensitive headers are stripped during redirects.
912 //The `follow-redirects` library removes credentials on protocol downgrade (HTTPS β†’ HTTP) for security.
913 //Since `beforeRedirect` runs after this, re-injecting credentials without checking the protocol can expose sensitive data.
914 //Always ensure credentials are only added for trusted HTTPS destinations.
915
916// Security note:
917// The beforeRedirect hook runs after sensitive headers are stripped during redirects.
918// Re-injecting credentials without checking the destination can expose sensitive data.
919// Only add credentials for trusted HTTPS destinations.
920// Avoid re-adding credentials on downgraded redirects.
921
922
923 // `socketPath` defines a UNIX Socket to be used in node.js.
924 // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
925 // Only either `socketPath` or `proxy` can be specified.
926 // If both are specified, `socketPath` is used.
927 //
928 // Security: when `socketPath` is set, hostname/port of the URL are ignored,
929 // which bypasses hostname-based SSRF protections. Never derive `socketPath`
930 // from untrusted input. Use `allowedSocketPaths` (below) to restrict accepted
931 // socket paths for defense-in-depth.
932 socketPath: null, // default
933
934 // `allowedSocketPaths` restricts which `socketPath` values are accepted.
935 // Accepts a string or array of strings. Entries and the incoming socketPath
936 // are compared after path.resolve(). A mismatch throws AxiosError with code
937 // `ERR_BAD_OPTION_VALUE`. When null/undefined, no restriction is applied.
938 allowedSocketPaths: null, // default
939
940 // `transport` determines the transport method that will be used to make the request.
941 // If defined, it will be used. Otherwise, if `maxRedirects` is 0,
942 // the default `http` or `https` library will be used, depending on the protocol specified in `protocol`.
943 // Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol,
944 // which can handle redirects.
945 transport: undefined, // default
946
947 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
948 // and https requests, respectively, in node.js. This allows options to be added like
949 // `keepAlive` that are not enabled by default before Node.js v19.0.0. After Node.js
950 // v19.0.0, you no longer need to customize the agent to enable `keepAlive` because
951 // `http.globalAgent` has `keepAlive` enabled by default.
952 httpAgent: new http.Agent({ keepAlive: true }),
953 httpsAgent: new https.Agent({ keepAlive: true }),
954
955 // `proxy` defines the hostname, port, and protocol of the proxy server.
956 // You can also define your proxy using the conventional `http_proxy` and
957 // `https_proxy` environment variables. If you are using environment variables
958 // for your proxy configuration, you can also define a `no_proxy` environment
959 // variable as a comma-separated list of domains that should not be proxied.
960 // Use `false` to disable proxies, ignoring environment variables.
961 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
962 // supplies credentials.
963 // For `http://` targets, axios sends the request to the proxy in
964 // forward-proxy mode and stamps `Proxy-Authorization` onto the request
965 // headers (overwriting any user-supplied `Proxy-Authorization` header).
966 // For `https://` targets, axios establishes a CONNECT tunnel through the
967 // proxy and performs TLS end-to-end with the origin; `Proxy-Authorization`
968 // is sent on the CONNECT request only, never on the wrapped TLS request,
969 // so the proxy never sees the URL, headers, or body. Supply a custom
970 // `httpsAgent` to opt out of automatic CONNECT tunneling.
971 // If the proxy server uses HTTPS, then you must set the protocol to `https`.
972 // A user-supplied `Host` header in `headers` is preserved when forwarding
973 // through a proxy (case-insensitive match on `host`/`Host`/`HOST`); this
974 // lets you target a virtual host that differs from the request URL β€” for
975 // example, hitting `127.0.0.1:4000` while having the proxy treat the
976 // request as `example.com`. If no `Host` header is supplied, axios
977 // defaults it to the request URL's `hostname:port` as before. The Host
978 // header is only set in forward-proxy mode (HTTP targets); for HTTPS
979 // tunneling the Host header is sent inside the TLS connection, not seen
980 // by the proxy.
981 proxy: {
982 protocol: 'https',
983 host: '127.0.0.1',
984 // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
985 port: 9000,
986 auth: {
987 username: 'mikeymike',
988 password: 'rapunz3l'
989 }
990 },
991
992 // `cancelToken` specifies a cancel token that can be used to cancel the request
993 // (see Cancellation section below for details)
994 cancelToken: new CancelToken(function (cancel) {
995 }),
996
997 // an alternative way to cancel Axios requests using AbortController
998 signal: new AbortController().signal,
999
1000 // `decompress` indicates whether or not the response body should be decompressed
1001 // automatically. If set to `true` will also remove the 'content-encoding' header
1002 // from the responses objects of all decompressed responses
1003 // - Node only (XHR cannot turn off decompression)
1004 decompress: true, // default
1005
1006 // `insecureHTTPParser` boolean.
1007 // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
1008 // This may allow interoperability with non-conformant HTTP implementations.
1009 // Using the insecure parser should be avoided.
1010 // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
1011 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
1012 insecureHTTPParser: undefined, // default
1013
1014 // transitional options for backward compatibility that may be removed in the newer versions
1015 transitional: {
1016 // silent JSON parsing mode
1017 // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
1018 // `false` - throw SyntaxError if JSON parsing failed
1019 // Important: this option only takes effect when `responseType` is explicitly set to 'json'.
1020 // When `responseType` is omitted (defaults to no value), axios uses `forcedJSONParsing`
1021 // to attempt JSON parsing, but will silently return the raw string on failure regardless
1022 // of this setting. To have invalid JSON throw errors, use:
1023 // { responseType: 'json', transitional: { silentJSONParsing: false } }
1024 silentJSONParsing: true, // default value for the current Axios version
1025
1026 // try to parse the response string as JSON even if `responseType` is not 'json'
1027 forcedJSONParsing: true,
1028
1029 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
1030 clarifyTimeoutError: false,
1031
1032 // use the legacy interceptor request/response ordering
1033 legacyInterceptorReqResOrdering: true, // default
1034 },
1035
1036 env: {
1037 // The FormData class to be used to automatically serialize the payload into a FormData object
1038 FormData: window?.FormData || global?.FormData
1039 },
1040
1041 formSerializer: {
1042 visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
1043 dots: boolean; // use dots instead of brackets format
1044 metaTokens: boolean; // keep special endings like {} in parameter key
1045 indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
1046 maxDepth: 100; // maximum object nesting depth; throws AxiosError (ERR_FORM_DATA_DEPTH_EXCEEDED) if exceeded. Set to Infinity to disable.
1047 },
1048
1049 // http adapter only (node.js)
1050 maxRate: [
1051 100 * 1024, // 100KB/s upload limit,
1052 100 * 1024 // 100KB/s download limit
1053 ]
1054}
1055```
1056
1057### Strict RFC 3986 percent-encoding for query params
1058
1059By default, axios decodes `%3A`, `%24`, `%2C` and `%20` back to `:`, `$`, `,` and `+` for readability (the `+` follows the `application/x-www-form-urlencoded` convention for spaces in query strings). These characters are valid in a query component under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), so the default output is correct, but some backends require strict percent-encoding and reject the readable form.
1060
1061Override the default encoder via `paramsSerializer.encode`:
1062
1063```js
1064// Per-request: emit strict RFC 3986 percent-encoding for query values
1065axios.get('/foo', {
1066 params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
1067 paramsSerializer: { encode: encodeURIComponent }
1068});
1069
1070// Or set it on the instance defaults
1071const client = axios.create({
1072 paramsSerializer: { encode: encodeURIComponent }
1073});
1074```
1075
1076## πŸ”₯ HTTP/2 Support
1077
1078Axios has experimental HTTP/2 support available via the Node.js HTTP adapter.
1079
1080Support depends on the runtime environment and Node.js version. Features like redirects and some behaviors may not be fully supported with HTTP/2.
1081
1082Options like `httpVersion` and `http2Options` are adapter-specific and may not work consistently across all environments.
1083
1084If HTTP/2 functionality is required, ensure your runtime environment supports it or consider using alternative libraries or custom adapters.
1085
1086## Response Schema
1087
1088The response to a request contains the following information.
1089
1090```js
1091{
1092 // `data` is the response that was provided by the server
1093 data: {},
1094
1095 // `status` is the HTTP status code from the server response
1096 status: 200,
1097
1098 // `statusText` is the HTTP status message from the server response
1099 statusText: 'OK',
1100
1101 // `headers` the HTTP headers that the server responded with
1102 // All header names are lowercase and can be accessed using the bracket notation.
1103 // Example: `response.headers['content-type']`
1104 headers: {},
1105
1106 // `config` is the config that was provided to `axios` for the request
1107 config: {},
1108
1109 // `request` is the request that generated this response
1110 // It is the last ClientRequest instance in node.js (in redirects)
1111 // and an XMLHttpRequest instance in the browser
1112 request: {}
1113}
1114```
1115
1116When using `then`, you will receive the response as follows:
1117
1118```js
1119const response = await axios.get('/user/12345');
1120console.log(response.data);
1121console.log(response.status);
1122console.log(response.statusText);
1123console.log(response.headers);
1124console.log(response.config);
1125```
1126
1127When 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.
1128
1129## Config Defaults
1130
1131You can specify config defaults that will be applied to every request.
1132
1133### Global axios defaults
1134
1135```js
1136axios.defaults.baseURL = 'https://api.example.com';
1137
1138// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
1139// See below for an example using Custom instance defaults instead.
1140axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
1141
1142axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
1143```
1144
1145### Custom instance defaults
1146
1147```js
1148// Set config defaults when creating the instance
1149const instance = axios.create({
1150 baseURL: 'https://api.example.com',
1151});
1152
1153// Alter defaults after instance has been created
1154instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
1155```
1156
1157### Config order of precedence
1158
1159Config 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.
1160
1161```js
1162// Create an instance using the config defaults provided by the library
1163// At this point the timeout config value is `0` as is the default for the library
1164const instance = axios.create();
1165
1166// Override timeout default for the library
1167// Now all requests using this instance will wait 2.5 seconds before timing out
1168instance.defaults.timeout = 2500;
1169
1170// Override timeout for this request as it's known to take a long time
1171instance.get('/longRequest', {
1172 timeout: 5000,
1173});
1174```
1175
1176## Interceptors
1177
1178You can intercept requests or responses before methods like `.get()` or `.post()`
1179resolve their promises (before code inside `then` or `catch`, or after `await`)
1180
1181```js
1182const instance = axios.create();
1183
1184// Add a request interceptor
1185instance.interceptors.request.use(
1186 function (config) {
1187 // Do something before the request is sent
1188 return config;
1189 },
1190 function (error) {
1191 // Do something with the request error
1192 return Promise.reject(error);
1193 }
1194);
1195
1196// Add a response interceptor
1197instance.interceptors.response.use(
1198 function (response) {
1199 // Any status code that lies within the range of 2xx causes this function to trigger
1200 // Do something with response data
1201 return response;
1202 },
1203 function (error) {
1204 // Any status codes that fall outside the range of 2xx cause this function to trigger
1205 // Do something with response error
1206 return Promise.reject(error);
1207 }
1208);
1209```
1210
1211If you need to remove an interceptor later you can.
1212
1213```js
1214const instance = axios.create();
1215const myInterceptor = instance.interceptors.request.use(function () {
1216 /*...*/
1217});
1218instance.interceptors.request.eject(myInterceptor);
1219```
1220
1221You can also clear all interceptors for requests or responses.
1222
1223```js
1224const instance = axios.create();
1225instance.interceptors.request.use(function () {
1226 /*...*/
1227});
1228instance.interceptors.request.clear(); // Removes interceptors from requests
1229instance.interceptors.response.use(function () {
1230 /*...*/
1231});
1232instance.interceptors.response.clear(); // Removes interceptors from responses
1233```
1234
1235You can add interceptors to a custom instance of axios.
1236
1237```js
1238const instance = axios.create();
1239instance.interceptors.request.use(function () {
1240 /*...*/
1241});
1242```
1243
1244When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
1245in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
1246the interceptor and your request gets put at the bottom of the call stack). If your request interceptors are synchronous you can add a flag
1247to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
1248
1249```js
1250axios.interceptors.request.use(
1251 function (config) {
1252 config.headers.test = 'I am only a header!';
1253 return config;
1254 },
1255 null,
1256 { synchronous: true }
1257);
1258```
1259
1260If you want to execute a particular interceptor based on a runtime check,
1261you can add a `runWhen` function to the options object. The request interceptor will not be executed **if and only if** the return
1262of `runWhen` is `false`. The function will be called with the config
1263object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
1264asynchronous request interceptor that only needs to run at certain times.
1265
1266```js
1267function onGetCall(config) {
1268 return config.method === 'get';
1269}
1270axios.interceptors.request.use(
1271 function (config) {
1272 config.headers.test = 'special get headers';
1273 return config;
1274 },
1275 null,
1276 { runWhen: onGetCall }
1277);
1278```
1279
1280> **Note:** The options parameter(having `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment.
1281
1282### Interceptor Execution Order
1283
1284**Important:** Interceptors have different execution orders depending on their type!
1285
1286Request interceptors are executed in **reverse order** (LIFO - Last In, First Out). This means the _last_ interceptor added is executed **first**.
1287
1288Response interceptors are executed in the **order they were added** (FIFO - First In, First Out). This means the _first_ interceptor added is executed **first**.
1289
1290Example:
1291
1292```js
1293const instance = axios.create();
1294
1295const interceptor = (id) => (base) => {
1296 console.log(id);
1297 return base;
1298};
1299
1300instance.interceptors.request.use(interceptor('Request Interceptor 1'));
1301instance.interceptors.request.use(interceptor('Request Interceptor 2'));
1302instance.interceptors.request.use(interceptor('Request Interceptor 3'));
1303instance.interceptors.response.use(interceptor('Response Interceptor 1'));
1304instance.interceptors.response.use(interceptor('Response Interceptor 2'));
1305instance.interceptors.response.use(interceptor('Response Interceptor 3'));
1306
1307// Console output:
1308// Request Interceptor 3
1309// Request Interceptor 2
1310// Request Interceptor 1
1311// [HTTP request is made]
1312// Response Interceptor 1
1313// Response Interceptor 2
1314// Response Interceptor 3
1315```
1316
1317### Multiple Interceptors
1318
1319Given that you add multiple response interceptors
1320and when the response was fulfilled
1321
1322- then each interceptor is executed
1323- then they are executed in the order they were added
1324- then only the last interceptor's result is returned
1325- then every interceptor receives the result of its predecessor
1326- and when the fulfillment-interceptor throws
1327 - then the following fulfillment-interceptor is not called
1328 - then the following rejection-interceptor is called
1329 - once caught, another following fulfill-interceptor is called again (just like in a promise chain).
1330
1331Read [the interceptor tests](./test/specs/interceptors.spec.js) to see all this in code.
1332
1333## Error Types
1334
1335There are many different axios error messages that can appear which can provide basic information about the specifics of the error and where opportunities may lie in debugging.
1336
1337The general structure of axios errors is as follows:
1338| Property | Definition |
1339| -------- | ---------- |
1340| message | A quick summary of the error message and the status it failed with. |
1341| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. |
1342| stack | Provides the stack trace of the error. |
1343| config | An axios config object with specific instance configurations defined by the user from when the request was made |
1344| code | Represents an axios identified error. The table below lists specific definitions for internal axios error. |
1345| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings.
1346
1347Below is a list of potential axios identified error:
1348
1349| Code | Definition |
1350| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1351| ERR_BAD_OPTION_VALUE | Invalid value provided in axios configuration. |
1352| ERR_BAD_OPTION | Invalid option provided in axios configuration. |
1353| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. |
1354| ERR_DEPRECATED | Deprecated feature or method used in axios. |
1355| ERR_INVALID_URL | Invalid URL provided for axios request. |
1356| ECONNABORTED | Typically indicates that the request has been timed out (unless `transitional.clarifyTimeoutError` is set) or aborted by the browser or its plugin. |
1357| ERR_CANCELED | Feature or method is canceled explicitly by the user using an AbortSignal (or a CancelToken). |
1358| ETIMEDOUT | Request timed out due to exceeding the default axios timelimit. `transitional.clarifyTimeoutError` must be set to `true`, otherwise a generic `ECONNABORTED` error will be thrown instead. |
1359| 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. |
1360| ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration. |
1361| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with `5xx` status code. |
1362| ERR_BAD_REQUEST | The request has an unexpected format or is missing required parameters. Usually related to a response with `4xx` status code. |
1363
1364## Handling Errors
1365
1366The 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.
1367
1368```js
1369axios.get('/user/12345').catch(function (error) {
1370 if (error.response) {
1371 // The request was made and the server responded with a status code
1372 // that falls out of the range of 2xx
1373 console.log(error.response.data);
1374 console.log(error.response.status);
1375 console.log(error.response.headers);
1376 } else if (error.request) {
1377 // The request was made but no response was received
1378 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
1379 // http.ClientRequest in node.js
1380 console.log(error.request);
1381 } else {
1382 // Something happened in setting up the request that triggered an Error
1383 console.log('Error', error.message);
1384 }
1385 console.log(error.config);
1386});
1387```
1388
1389Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.
1390
1391```js
1392axios.get('/user/12345', {
1393 validateStatus: function (status) {
1394 return status < 500; // Resolve only if the status code is less than 500
1395 },
1396});
1397```
1398
1399Using `toJSON` you get an object with more information about the HTTP error.
1400
1401```js
1402axios.get('/user/12345').catch(function (error) {
1403 console.log(error.toJSON());
1404});
1405```
1406
1407To avoid logging secrets from `error.config`, pass a `redact` array in the request config. Matching config keys are masked case-insensitively at any depth when `AxiosError#toJSON()` is called.
1408
1409```js
1410axios.get('/user/12345', {
1411 headers: { Authorization: 'Bearer token' },
1412 redact: ['authorization']
1413}).catch(function (error) {
1414 console.log(error.toJSON().config.headers.Authorization); // [REDACTED ****]
1415});
1416```
1417
1418## Handling Timeouts
1419
1420```js
1421async function fetchWithTimeout() {
1422 try {
1423 const response = await axios.get('https://example.com/data', {
1424 timeout: 5000, // 5 seconds
1425 transitional: {
1426 // set to true if you prefer ETIMEDOUT over ECONNABORTED
1427 clarifyTimeoutError: false,
1428 },
1429 });
1430
1431 console.log('Response:', response.data);
1432 } catch (error) {
1433 if (axios.isAxiosError(error)) {
1434 if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
1435 console.error('Request timed out. Please try again.');
1436 return;
1437 }
1438
1439 console.error('Axios error:', error.message);
1440 return;
1441 }
1442
1443 console.error('Unexpected error:', error);
1444 }
1445}
1446```
1447
1448## Cancellation
1449
1450### AbortController
1451
1452Starting from `v0.22.0` Axios supports AbortController to cancel requests in a fetch API way:
1453
1454```js
1455const controller = new AbortController();
1456
1457axios
1458 .get('/foo/bar', {
1459 signal: controller.signal,
1460 })
1461 .then(function (response) {
1462 //...
1463 });
1464// cancel the request
1465controller.abort();
1466```
1467
1468### CancelToken `πŸ‘Ždeprecated`
1469
1470You can also cancel a request using a _CancelToken_.
1471
1472> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
1473
1474> This API is deprecated since v0.22.0 and shouldn't be used in new projects
1475
1476You can create a cancel token using the `CancelToken.source` factory as shown below:
1477
1478```js
1479const CancelToken = axios.CancelToken;
1480const source = CancelToken.source();
1481
1482axios
1483 .get('/user/12345', {
1484 cancelToken: source.token,
1485 })
1486 .catch(function (thrown) {
1487 if (axios.isCancel(thrown)) {
1488 console.log('Request canceled', thrown.message);
1489 } else {
1490 // handle error
1491 }
1492 });
1493
1494axios.post(
1495 '/user/12345',
1496 {
1497 name: 'new name',
1498 },
1499 {
1500 cancelToken: source.token,
1501 }
1502);
1503
1504// cancel the request (the message parameter is optional)
1505source.cancel('Operation canceled by the user.');
1506```
1507
1508You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
1509
1510```js
1511const CancelToken = axios.CancelToken;
1512let cancel;
1513
1514axios.get('/user/12345', {
1515 cancelToken: new CancelToken(function executor(c) {
1516 // An executor function receives a cancel function as a parameter
1517 cancel = c;
1518 }),
1519});
1520
1521// cancel the request
1522cancel();
1523```
1524
1525> **Note:** you can cancel several requests with the same cancel token/abort controller.
1526> 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.
1527
1528> During the transition period, you can use both cancellation APIs, even for the same request:
1529
1530## Using `application/x-www-form-urlencoded` format
1531
1532### URLSearchParams
1533
1534By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) format 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).
1535
1536```js
1537const params = new URLSearchParams({ foo: 'bar' });
1538params.append('extraparam', 'value');
1539axios.post('/foo', params);
1540```
1541
1542### Query string (Older browsers)
1543
1544For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
1545
1546Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
1547
1548```js
1549const qs = require('qs');
1550axios.post('/foo', qs.stringify({ bar: 123 }));
1551```
1552
1553Or in another way (ES6),
1554
1555```js
1556import qs from 'qs';
1557const data = { bar: 123 };
1558const options = {
1559 method: 'POST',
1560 headers: { 'content-type': 'application/x-www-form-urlencoded' },
1561 data: qs.stringify(data),
1562 url,
1563};
1564axios(options);
1565```
1566
1567### Older Node.js versions
1568
1569For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
1570
1571```js
1572const querystring = require('querystring');
1573axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
1574```
1575
1576You can also use the [`qs`](https://github.com/ljharb/qs) library.
1577
1578> **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.
1579
1580### πŸ†• Automatic serialization to URLSearchParams
1581
1582Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
1583
1584```js
1585const data = {
1586 x: 1,
1587 arr: [1, 2, 3],
1588 arr2: [1, [2], 3],
1589 users: [
1590 { name: 'Peter', surname: 'Griffin' },
1591 { name: 'Thomas', surname: 'Anderson' },
1592 ],
1593};
1594
1595await axios.postForm('https://postman-echo.com/post', data, {
1596 headers: { 'content-type': 'application/x-www-form-urlencoded' },
1597});
1598```
1599
1600The server will handle it as:
1601
1602```js
1603 {
1604 x: '1',
1605 'arr[]': [ '1', '2', '3' ],
1606 'arr2[0]': '1',
1607 'arr2[1][0]': '2',
1608 'arr2[2]': '3',
1609 'arr3[]': [ '1', '2', '3' ],
1610 'users[0][name]': 'Peter',
1611 'users[0][surname]': 'griffin',
1612 'users[1][name]': 'Thomas',
1613 'users[1][surname]': 'Anderson'
1614 }
1615```
1616
1617If 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
1618
1619```js
1620const app = express();
1621
1622app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
1623
1624app.post('/', function (req, res, next) {
1625 // echo body as JSON
1626 res.send(JSON.stringify(req.body));
1627});
1628
1629server = app.listen(3000);
1630```
1631
1632## Using `multipart/form-data` format
1633
1634### FormData
1635
1636To send the data as a `multipart/form-data` you need to pass a formData instance as a payload.
1637Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.
1638
1639```js
1640const formData = new FormData();
1641formData.append('foo', 'bar');
1642
1643axios.post('https://httpbin.org/post', formData);
1644```
1645
1646In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
1647
1648```js
1649const FormData = require('form-data');
1650
1651const form = new FormData();
1652form.append('my_field', 'my value');
1653form.append('my_buffer', Buffer.alloc(10));
1654form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
1655
1656axios.post('https://example.com', form);
1657```
1658
1659In node.js, when a `FormData` object provides `getHeaders()`, axios copies all returned headers by default for v1 compatibility. If the `FormData` object is custom or not fully trusted, set `formDataHeaderPolicy: 'content-only'` to copy only `Content-Type` and `Content-Length`, and set any other request headers explicitly with the request `headers` config.
1660
1661### πŸ†• Automatic serialization to FormData
1662
1663Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
1664header is set to `multipart/form-data`.
1665
1666The following request will submit the data in a FormData format (Browser & Node.js):
1667
1668```js
1669import axios from 'axios';
1670
1671axios
1672 .post(
1673 'https://httpbin.org/post',
1674 { x: 1 },
1675 {
1676 headers: {
1677 'Content-Type': 'multipart/form-data',
1678 },
1679 }
1680 )
1681 .then(({ data }) => console.log(data));
1682```
1683
1684In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
1685
1686You can overload the FormData class by setting the `env.FormData` config variable,
1687but you probably won't need it in most cases:
1688
1689```js
1690const axios = require('axios');
1691var FormData = require('form-data');
1692
1693axios
1694 .post(
1695 'https://httpbin.org/post',
1696 { x: 1, buf: Buffer.alloc(10) },
1697 {
1698 headers: {
1699 'Content-Type': 'multipart/form-data',
1700 },
1701 }
1702 )
1703 .then(({ data }) => console.log(data));
1704```
1705
1706Axios FormData serializer supports some special endings to perform the following operations:
1707
1708- `{}` - serialize the value with JSON.stringify
1709- `[]` - unwrap the array-like object as separate fields with the same key
1710
1711> **Note**: unwrap/expand operation will be used by default on arrays and FileList objects
1712
1713FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
1714
1715- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object
1716 to a `FormData` object by following custom rules.
1717
1718- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
1719
1720- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
1721 The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.
1722
1723- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects.
1724 - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
1725 - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
1726 - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
1727- `maxDepth: number = 100` - maximum object nesting depth the serializer will recurse into. If the
1728 input object exceeds this depth, an `AxiosError` with `code: 'ERR_FORM_DATA_DEPTH_EXCEEDED'` is
1729 thrown instead of overflowing the call stack. This protects server-side applications from DoS
1730 attacks via deeply nested payloads. Set to `Infinity` to disable the limit and restore pre-fix behaviour.
1731
1732```js
1733// Raise the limit for a schema that genuinely nests deeper than 100 levels:
1734axios.postForm('/api', data, { formSerializer: { maxDepth: 200 } });
1735
1736// Same protection applies to params serialization:
1737axios.get('/api', { params: data, paramsSerializer: { maxDepth: 200 } });
1738```
1739
1740Let's say we have an object like this one:
1741
1742```js
1743const obj = {
1744 x: 1,
1745 arr: [1, 2, 3],
1746 arr2: [1, [2], 3],
1747 users: [
1748 { name: 'Peter', surname: 'Griffin' },
1749 { name: 'Thomas', surname: 'Anderson' },
1750 ],
1751 'obj2{}': [{ x: 1 }],
1752};
1753```
1754
1755The following steps will be executed by the Axios serializer internally:
1756
1757```js
1758const formData = new FormData();
1759formData.append('x', '1');
1760formData.append('arr[]', '1');
1761formData.append('arr[]', '2');
1762formData.append('arr[]', '3');
1763formData.append('arr2[0]', '1');
1764formData.append('arr2[1][0]', '2');
1765formData.append('arr2[2]', '3');
1766formData.append('users[0][name]', 'Peter');
1767formData.append('users[0][surname]', 'Griffin');
1768formData.append('users[1][name]', 'Thomas');
1769formData.append('users[1][surname]', 'Anderson');
1770formData.append('obj2{}', '[{"x":1}]');
1771```
1772
1773Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
1774which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.
1775
1776## Files Posting
1777
1778You can easily submit a single file:
1779
1780```js
1781await axios.postForm('https://httpbin.org/post', {
1782 myVar: 'foo',
1783 file: document.querySelector('#fileInput').files[0],
1784});
1785```
1786
1787or multiple files as `multipart/form-data`:
1788
1789```js
1790await axios.postForm('https://httpbin.org/post', {
1791 'files[]': document.querySelector('#fileInput').files,
1792});
1793```
1794
1795`FileList` object can be passed directly:
1796
1797```js
1798await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files);
1799```
1800
1801All files will be sent with the same field names: `files[]`.
1802
1803## πŸ†• HTML Form Posting (browser)
1804
1805Pass an HTML Form element as a payload to submit it as `multipart/form-data` content.
1806
1807```js
1808await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
1809```
1810
1811`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
1812
1813```js
1814await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
1815 headers: {
1816 'Content-Type': 'application/json',
1817 },
1818});
1819```
1820
1821For example, the Form
1822
1823```html
1824<form id="form">
1825 <input type="text" name="foo" value="1" />
1826 <input type="text" name="deep.prop" value="2" />
1827 <input type="text" name="deep prop spaced" value="3" />
1828 <input type="text" name="baz" value="4" />
1829 <input type="text" name="baz" value="5" />
1830
1831 <select name="user.age">
1832 <option value="value1">Value 1</option>
1833 <option value="value2" selected>Value 2</option>
1834 <option value="value3">Value 3</option>
1835 </select>
1836
1837 <input type="submit" value="Save" />
1838</form>
1839```
1840
1841will be submitted as the following JSON object:
1842
1843```js
1844{
1845 "foo": "1",
1846 "deep": {
1847 "prop": {
1848 "spaced": "3"
1849 }
1850 },
1851 "baz": [
1852 "4",
1853 "5"
1854 ],
1855 "user": {
1856 "age": "value2"
1857 }
1858}
1859```
1860
1861Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.
1862
1863## πŸ†• Progress capturing
1864
1865Axios supports both browser and node environments to capture request upload/download progress.
1866The frequency of progress events is forced to be limited to `3` times per second.
1867
1868```js
1869await axios.post(url, data, {
1870 onUploadProgress: function (axiosProgressEvent) {
1871 /*{
1872 loaded: number;
1873 total?: number;
1874 progress?: number; // in range [0..1]
1875 bytes: number; // how many bytes have been transferred since the last trigger (delta)
1876 estimated?: number; // estimated time in seconds
1877 rate?: number; // upload speed in bytes
1878 upload: true; // upload sign
1879 }*/
1880 },
1881
1882 onDownloadProgress: function (axiosProgressEvent) {
1883 /*{
1884 loaded: number;
1885 total?: number;
1886 progress?: number;
1887 bytes: number;
1888 estimated?: number;
1889 rate?: number; // download speed in bytes
1890 download: true; // download sign
1891 }*/
1892 },
1893});
1894```
1895
1896You can also track stream upload/download progress in node.js:
1897
1898```js
1899const { data } = await axios.post(SERVER_URL, readableStream, {
1900 onUploadProgress: ({ progress }) => {
1901 console.log((progress * 100).toFixed(2));
1902 },
1903
1904 headers: {
1905 'Content-Length': contentLength,
1906 },
1907
1908 maxRedirects: 0, // avoid buffering the entire stream
1909});
1910```
1911
1912> **Note:**
1913> Capturing FormData upload progress is not currently supported in node.js environments.
1914
1915> **⚠️ Warning**
1916> It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the **node.js** environment,
1917> as the follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm.
1918
1919## πŸ†• Rate limiting
1920
1921Download and upload rate limits can only be set for the http adapter (node.js):
1922
1923```js
1924const { data } = await axios.post(LOCAL_SERVER_URL, myBuffer, {
1925 onUploadProgress: ({ progress, rate }) => {
1926 console.log(`Upload [${(progress * 100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`);
1927 },
1928
1929 maxRate: [100 * 1024], // 100KB/s limit
1930});
1931```
1932
1933## πŸ†• AxiosHeaders
1934
1935Axios has its own `AxiosHeaders` class to manipulate headers using a Map-like API that guarantees caseless work.
1936Although HTTP is case-insensitive in headers, Axios will retain the case of the original header for stylistic reasons
1937and as a workaround when servers mistakenly consider the header's case.
1938The old approach of directly manipulating the headers object is still available, but deprecated and not recommended for future usage.
1939
1940### Working with headers
1941
1942An AxiosHeaders object instance can contain different types of internal values. that control setting and merging logic.
1943The final headers object with string values is obtained by Axios by calling the `toJSON` method.
1944
1945> Note: By JSON here we mean an object consisting only of string values intended to be sent over the network.
1946
1947The header value can be one of the following types:
1948
1949- `string` - normal string value that will be sent to the server
1950- `null` - skip header when rendering to JSON
1951- `false` - skip header when rendering to JSON, additionally indicates that `set` method must be called with `rewrite` option set to `true`
1952 to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`)
1953- `undefined` - value is not set
1954
1955> Note: The header value is considered set if it is not equal to undefined.
1956
1957The headers object is always initialized inside interceptors and transformers:
1958
1959```ts
1960axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
1961 request.headers.set('My-header', 'value');
1962
1963 request.headers.set({
1964 'My-set-header1': 'my-set-value1',
1965 'My-set-header2': 'my-set-value2',
1966 });
1967
1968 request.headers.set('User-Agent', false); // disable subsequent setting the header by Axios
1969
1970 request.headers.setContentType('text/plain');
1971
1972 request.headers['My-set-header2'] = 'newValue'; // direct access is deprecated
1973
1974 return request;
1975});
1976```
1977
1978You can iterate over an `AxiosHeaders` instance using a `for...of` statement:
1979
1980```js
1981const headers = new AxiosHeaders({
1982 foo: '1',
1983 bar: '2',
1984 baz: '3',
1985});
1986
1987for (const [header, value] of headers) {
1988 console.log(header, value);
1989}
1990
1991// foo 1
1992// bar 2
1993// baz 3
1994```
1995
1996### Preserving a specific header case
1997
1998Header names are case-insensitive, but `AxiosHeaders` keeps the case of the first matching key it sees.
1999If you need a specific case for non-standard case-sensitive servers, define a case preset with `undefined` and then set the value later:
2000
2001```js
2002const api = axios.create();
2003
2004api.defaults.headers.common = {
2005 'content-type': undefined,
2006 accept: undefined,
2007};
2008
2009await api.put(url, data, {
2010 headers: {
2011 'Content-Type': 'application/octet-stream',
2012 Accept: 'application/json',
2013 },
2014});
2015```
2016
2017You can also compose the same behavior with `AxiosHeaders.concat`:
2018
2019```js
2020const headers = axios.AxiosHeaders.concat(
2021 { 'content-type': undefined },
2022 { 'Content-Type': 'application/octet-stream' }
2023);
2024
2025await axios.put(url, data, { headers });
2026```
2027
2028### new AxiosHeaders(headers?)
2029
2030Constructs a new `AxiosHeaders` instance.
2031
2032```
2033constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
2034```
2035
2036If the headers object is a string, it will be parsed as RAW HTTP headers.
2037
2038```js
2039const headers = new AxiosHeaders(`
2040Host: www.bing.com
2041User-Agent: curl/7.54.0
2042Accept: */*`);
2043
2044console.log(headers);
2045
2046// Object [AxiosHeaders] {
2047// host: 'www.bing.com',
2048// 'user-agent': 'curl/7.54.0',
2049// accept: '*/*'
2050// }
2051```
2052
2053### AxiosHeaders#set
2054
2055```ts
2056set(headerName, value: Axios, rewrite?: boolean);
2057set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean);
2058set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean);
2059```
2060
2061The `rewrite` argument controls the overwriting behavior:
2062
2063- `false` - do not overwrite if the header's value is set (is not `undefined`)
2064- `undefined` (default) - overwrite the header unless its value is set to `false`
2065- `true` - rewrite anyway
2066
2067The option can also accept a user-defined function that determines whether the value should be overwritten or not.
2068
2069Returns `this`.
2070
2071### AxiosHeaders#get(header)
2072
2073```
2074 get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
2075 get(headerName: string, parser: RegExp): RegExpExecArray | null;
2076```
2077
2078Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`,
2079matcher function or internal key-value parser.
2080
2081```ts
2082const headers = new AxiosHeaders({
2083 'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h',
2084});
2085
2086console.log(headers.get('Content-Type'));
2087// multipart/form-data; boundary=Asrf456BGe4h
2088
2089console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters:
2090// [Object: null prototype] {
2091// 'multipart/form-data': undefined,
2092// boundary: 'Asrf456BGe4h'
2093// }
2094
2095console.log(
2096 headers.get('Content-Type', (value, name, headers) => {
2097 return String(value).replace(/a/g, 'ZZZ');
2098 })
2099);
2100// multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h
2101
2102console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]);
2103// boundary=Asrf456BGe4h
2104```
2105
2106Returns the value of the header.
2107
2108### AxiosHeaders#has(header, matcher?)
2109
2110```
2111has(header: string, matcher?: AxiosHeaderMatcher): boolean;
2112```
2113
2114Returns `true` if the header is set (has no `undefined` value).
2115
2116### AxiosHeaders#delete(header, matcher?)
2117
2118```
2119delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
2120```
2121
2122Returns `true` if at least one header has been removed.
2123
2124### AxiosHeaders#clear(matcher?)
2125
2126```
2127clear(matcher?: AxiosHeaderMatcher): boolean;
2128```
2129
2130Removes all headers.
2131Unlike the `delete` method matcher, this optional matcher will be used to match against the header name rather than the value.
2132
2133```ts
2134const headers = new AxiosHeaders({
2135 foo: '1',
2136 'x-foo': '2',
2137 'x-bar': '3',
2138});
2139
2140console.log(headers.clear(/^x-/)); // true
2141
2142console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' }
2143```
2144
2145Returns `true` if at least one header has been cleared.
2146
2147### AxiosHeaders#normalize(format);
2148
2149If the headers object was changed directly, it can have duplicates with the same name but in different cases.
2150This method normalizes the headers object by combining duplicate keys into one.
2151Axios uses this method internally after calling each interceptor.
2152Set `format` to true for converting header names to lowercase and capitalizing the initial letters (`cOntEnt-type` => `Content-Type`)
2153
2154```js
2155const headers = new AxiosHeaders({
2156 foo: '1',
2157});
2158
2159headers.Foo = '2';
2160headers.FOO = '3';
2161
2162console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' }
2163console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' }
2164console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' }
2165```
2166
2167Returns `this`.
2168
2169### AxiosHeaders#concat(...targets)
2170
2171```
2172concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
2173```
2174
2175Merges the instance with targets into a new `AxiosHeaders` instance. If the target is a string, it will be parsed as RAW HTTP headers.
2176
2177Returns a new `AxiosHeaders` instance.
2178
2179### AxiosHeaders#toJSON(asStrings?)
2180
2181```
2182toJSON(asStrings?: boolean): RawAxiosHeaders;
2183```
2184
2185Resolve all internal header values into a new null prototype object.
2186Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas.
2187
2188### AxiosHeaders.from(thing?)
2189
2190```
2191from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
2192```
2193
2194Returns a new `AxiosHeaders` instance created from the raw headers passed in,
2195or simply returns the given headers object if it's an `AxiosHeaders` instance.
2196
2197### AxiosHeaders.concat(...targets)
2198
2199```
2200concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
2201```
2202
2203Returns a new `AxiosHeaders` instance created by merging the target objects.
2204
2205### Shortcuts
2206
2207The following shortcuts are available:
2208
2209- `setContentType`, `getContentType`, `hasContentType`
2210
2211- `setContentLength`, `getContentLength`, `hasContentLength`
2212
2213- `setAccept`, `getAccept`, `hasAccept`
2214
2215- `setUserAgent`, `getUserAgent`, `hasUserAgent`
2216
2217- `setContentEncoding`, `getContentEncoding`, `hasContentEncoding`
2218
2219## πŸ”₯ Fetch adapter
2220
2221Fetch adapter was introduced in `v1.7.0`. By default, it will be used if `xhr` and `http` adapters are not available in the build,
2222or not supported by the environment.
2223To use it by default, it must be selected explicitly:
2224
2225```js
2226const { data } = axios.get(url, {
2227 adapter: 'fetch', // by default ['xhr', 'http', 'fetch']
2228});
2229```
2230
2231You can create a separate instance for this:
2232
2233```js
2234const fetchAxios = axios.create({
2235 adapter: 'fetch',
2236});
2237
2238const { data } = fetchAxios.get(url);
2239```
2240
2241The adapter supports the same functionality as the `xhr` adapter, **including upload and download progress capturing**.
2242Also, it supports additional response types such as `stream` and `formdata` (if supported by the environment).
2243
2244### πŸ”₯ Custom fetch
2245
2246Starting from `v1.12.0`, you can customize the fetch adapter to use a custom fetch API instead of environment globals.
2247You can pass a custom `fetch` function, `Request`, and `Response` constructors via env config.
2248This can be helpful in case of custom environments & app frameworks.
2249
2250Also, 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.
2251If your custom fetch api does not have these objects, and the globals are incompatible with a custom fetch,
2252you must disable their use inside the fetch adapter by passing null.
2253
2254> Note: Setting `Request` & `Response` to `null` will make it impossible for the fetch adapter to capture the upload & download progress.
2255
2256Basic example:
2257
2258```js
2259import customFetchFunction from 'customFetchModule';
2260
2261const instance = axios.create({
2262 adapter: 'fetch',
2263 onDownloadProgress(e) {
2264 console.log('downloadProgress', e);
2265 },
2266 env: {
2267 fetch: customFetchFunction,
2268 Request: null, // undefined -> use the global constructor
2269 Response: null,
2270 },
2271});
2272```
2273
2274#### πŸ”₯ Using with Tauri
2275
2276A 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.
2277
2278```js
2279import { fetch } from '@tauri-apps/plugin-http';
2280import axios from 'axios';
2281
2282const instance = axios.create({
2283 adapter: 'fetch',
2284 onDownloadProgress(e) {
2285 console.log('downloadProgress', e);
2286 },
2287 env: {
2288 fetch,
2289 },
2290});
2291
2292const { data } = await instance.get('https://google.com');
2293```
2294
2295#### πŸ”₯ Using with SvelteKit
2296
2297[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,
2298which makes it incompatible with the standard URL API. So, Axios must be configured to use the custom fetch API:
2299
2300```js
2301export async function load({ fetch }) {
2302 const { data: post } = await axios.get('https://jsonplaceholder.typicode.com/posts/1', {
2303 adapter: 'fetch',
2304 env: {
2305 fetch,
2306 Request: null,
2307 Response: null,
2308 },
2309 });
2310
2311 return { post };
2312}
2313```
2314
2315#### HTTP/2 Support
2316
2317Axios supports HTTP/2 via the Node.js `http` adapter (introduced in v1.13.0).
2318
2319This support depends on the runtime environment. Since Axios relies on Node.js APIs, HTTP/2 functionality is available in supported Node.js versions, but may not work in other environments (such as Bun or Deno).
2320
2321Options like `httpVersion` and `http2Options` are adapter-specific and may not behave consistently across all environments.
2322
2323Note: HTTP/2 redirects are currently not supported by the HTTP/2 adapter.
2324
2325```js
2326const form = new FormData();
2327
2328form.append('foo', '123');
2329
2330const { data, headers, status } = await axios.post('https://httpbin.org/post', form, {
2331 onUploadProgress(e) {
2332 console.log('upload progress', e);
2333 },
2334 onDownloadProgress(e) {
2335 console.log('download progress', e);
2336 },
2337 responseType: 'arraybuffer',
2338});
2339```
2340
2341## Semver
2342
2343Since Axios has reached a `v.1.0.0` we will fully embrace semver as per the spec [here](https://semver.org/)
2344
2345## Promises
2346
2347axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises).
2348If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
2349
2350## TypeScript
2351
2352axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors.
2353
2354```typescript
2355let user: User = null;
2356try {
2357 const { data } = await axios.get('/user?ID=12345');
2358 user = data.userDetails;
2359} catch (error) {
2360 if (axios.isAxiosError(error)) {
2361 handleAxiosError(error);
2362 } else {
2363 handleUnexpectedError(error);
2364 }
2365}
2366```
2367
2368Because axios dual publishes with an ESM default export and a CJS `module.exports`, there are some caveats.
2369The recommended setting is to use `"moduleResolution": "node16"` (this is implied by `"module": "node16"`). Note that this requires TypeScript 4.7 or greater.
2370If use ESM, your settings should be fine.
2371If you compile TypeScript to CJS and you can’t use `"moduleResolution": "node 16"`, you have to enable `esModuleInterop`.
2372If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`.
2373
2374You can also create a custom instance with typed interceptors:
2375
2376```typescript
2377import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
2378
2379const apiClient: AxiosInstance = axios.create({
2380 baseURL: 'https://api.example.com',
2381 timeout: 10000,
2382});
2383
2384apiClient.interceptors.request.use((config: InternalAxiosRequestConfig) => {
2385 // Add auth token
2386 return config;
2387});
2388```
2389
2390## Online one-click setup
2391
2392You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online.
2393
2394[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js)
2395
2396## Contributing
2397
2398### Local setup
2399
2400As a supply-chain hardening measure, this repository ships a project-level `.npmrc` that sets `ignore-scripts=true`. This blocks npm lifecycle scripts (`preinstall`, `install`, `postinstall`, `prepare`) from any direct or transitive dependency when you run `npm install` or `npm ci` inside the repo. See [THREATMODEL.md](./THREATMODEL.md) (threat T-S2) for the rationale.
2401
2402One consequence: the repository's own `prepare` hook (which installs Husky's git hooks) will **not** run automatically. After your first install, enable the git hooks manually:
2403
2404```bash
2405npm ci
2406npm rebuild husky && npx husky
2407```
2408
2409Run those two commands once per fresh checkout. You do **not** need to re-run them after every subsequent `npm install`.
2410
2411Do not remove `ignore-scripts=true` from `.npmrc` to "fix" this β€” that re-opens the lifecycle-script attack surface for every other package in the tree. All CI workflows already invoke npm with `--ignore-scripts`, so local behaviour matches CI.
2412
2413## Resources
2414
2415- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
2416- [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
2417- [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
2418- [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md)
2419
2420## Credits
2421
2422axios 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.
2423
2424## License
2425
2426[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
Note: See TracBrowser for help on using the repository browser.