source: node_modules/axios/README.md@ ff72ad2

Last change on this file since ff72ad2 was ff72ad2, checked in by ste08 <sjovanoska@…>, 2 months ago

Adding review works\!

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