strong-tie/inbound-calls
0
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=oss-sponsorship&utm_medium=paid_sponsorship&utm_content=website-link&utm_campaign=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=oss-sponsorship&utm_medium=paid_sponsorship&utm_content=website-link&utm_campaign=axios-http"><b>Website</b></a> | <a href="https://stytch.com/docs?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_content=docs-link&utm_campaign=axios-http"><b>Documentation</b></a> | <a href="https://github.com/stytchauth/stytch-node?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_content=node-sdk&utm_campaign=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=axios&utm_medium=sponsorlist&utm_campaign=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=axios&utm_medium=readme_sponsorlist&utm_campaign=sponsorship"><b>www.principal.com</b></a> </p>4</td><td align="center" width="33.333333333333336%"> <a href="https://www.descope.com/?utm_source=axios&utm_medium=referral&utm_campaign=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'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'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=axios&utm_medium=referral&utm_campaign=axios-oss-sponsorship"><b>Website</b></a> | <a href="https://docs.descope.com/?utm_source=axios&utm_medium=referral&utm_campaign=axios-oss-sponsorship"><b>Documentation</b></a> | <a href="https://www.descope.com/community?utm_source=axios&utm_medium=referral&utm_campaign=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=axios&utm_medium=sponsorlist&utm_campaign=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'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=axios&utm_medium=readme_sponsorlist&utm_campaign=sponsorship"><b>buzzoid.com</b></a> </p>6</td><td align="center" width="33.333333333333336%"> <a href="https://www.famety.com/buy-tiktok-likes?utm_source=axios&utm_medium=sponsorlist&utm_campaign=sponsorship" style="padding: 10px; display: inline-block"> <img width="70px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/famety-buy-instagram-followers.png" alt="Famety - Buy Instagram Followers"/> </a> <p align="center" title="At Famety, you can grow your social media following quickly, safely, and easily with just a few clicks. Rated the worldβs #1 social media service since 2013.">At Famety, you can grow your social media following quickly, safely, and easily with just a few clic...</p> <p align="center"> <a href="https://www.famety.com/buy-tiktok-likes?utm_source=axios&utm_medium=readme_sponsorlist&utm_campaign=sponsorship"><b>www.famety.com</b></a> </p>7</td><td align="center" width="33.333333333333336%"> <a href="https://poprey.com/?utm_source=axios&utm_medium=sponsorlist&utm_campaign=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=axios&utm_medium=readme_sponsorlist&utm_campaign=sponsorship"><b>poprey.com</b></a> </p>8</td></tr><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://opencollective.com/axios/contribute">π Become a sponsor</a>9</td><td align="center" width="33.333333333333336%"> <a href="https://opencollective.com/axios/contribute">π Become a sponsor</a>10</td><td align="center" width="33.333333333333336%"> <a href="https://opencollective.com/axios/contribute">π Become a sponsor</a>11</td></tr></table>12 13<!--<div>marker</div>-->14<br><br>15<div align="center">16 <a href="https://axios-http.com"><img src="https://axios-http.com/assets/logo.svg" /></a><br>17</div>18 19<p align="center">Promise based HTTP client for the browser and node.js</p>20 21<p align="center">22 <a href="https://axios-http.com/"><b>Website</b></a> β’23 <a href="https://axios-http.com/docs/intro"><b>Documentation</b></a>24</p>25 26<div align="center">27 28[](https://www.npmjs.org/package/axios)29[](https://cdnjs.com/libraries/axios)30[](https://github.com/axios/axios/actions/workflows/ci.yml)31[](https://gitpod.io/#https://github.com/axios/axios)32[](https://coveralls.io/r/mzabriskie/axios)33[](https://packagephobia.now.sh/result?p=axios)34[](https://bundlephobia.com/package/axios@latest)35[](https://npm-stat.com/charts.html?package=axios)36[](https://gitter.im/mzabriskie/axios)37[](https://www.codetriage.com/axios/axios)38[](https://snyk.io/test/npm/axios)39 40 41 42 43</div>44 45## Table of Contents46 47 - [Features](#features)48 - [Browser Support](#browser-support)49 - [Installing](#installing)50 - [Package manager](#package-manager)51 - [CDN](#cdn)52 - [Example](#example)53 - [Axios API](#axios-api)54 - [Request method aliases](#request-method-aliases)55 - [Concurrency π](#concurrency-deprecated)56 - [Creating an instance](#creating-an-instance)57 - [Instance methods](#instance-methods)58 - [Request Config](#request-config)59 - [Response Schema](#response-schema)60 - [Config Defaults](#config-defaults)61 - [Global axios defaults](#global-axios-defaults)62 - [Custom instance defaults](#custom-instance-defaults)63 - [Config order of precedence](#config-order-of-precedence)64 - [Interceptors](#interceptors)65 - [Multiple Interceptors](#multiple-interceptors)66 - [Handling Errors](#handling-errors)67 - [Cancellation](#cancellation)68 - [AbortController](#abortcontroller)69 - [CancelToken π](#canceltoken-deprecated)70 - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)71 - [URLSearchParams](#urlsearchparams)72 - [Query string](#query-string-older-browsers)73 - [π Automatic serialization](#-automatic-serialization-to-urlsearchparams)74 - [Using multipart/form-data format](#using-multipartform-data-format)75 - [FormData](#formdata)76 - [π Automatic serialization](#-automatic-serialization-to-formdata)77 - [Files Posting](#files-posting)78 - [HTML Form Posting](#-html-form-posting-browser)79 - [π Progress capturing](#-progress-capturing)80 - [π Rate limiting](#-progress-capturing)81 - [π AxiosHeaders](#-axiosheaders)82 - [π₯ Fetch adapter](#-fetch-adapter)83 - [Semver](#semver)84 - [Promises](#promises)85 - [TypeScript](#typescript)86 - [Resources](#resources)87 - [Credits](#credits)88 - [License](#license)89 90## Features91 92- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser93- Make [http](https://nodejs.org/api/http.html) requests from node.js94- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API95- Intercept request and response96- Transform request and response data97- Cancel requests98- Automatic transforms for [JSON](https://www.json.org/json-en.html) data99- π Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings100- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)101 102## Browser Support103 104 |  |  |  |  |105--- | --- | --- | --- | --- |106Latest β | Latest β | Latest β | Latest β | Latest β | 11 β |107 108[](https://saucelabs.com/u/axios)109 110## Installing111 112### Package manager113 114Using npm:115 116```bash117$ npm install axios118```119 120Using bower:121 122```bash123$ bower install axios124```125 126Using yarn:127 128```bash129$ yarn add axios130```131 132Using pnpm:133 134```bash135$ pnpm add axios136```137 138Once the package is installed, you can import the library using `import` or `require` approach:139 140```js141import axios, {isCancel, AxiosError} from 'axios';142```143 144You can also use the default export, since the named export is just a re-export from the Axios factory:145 146```js147import axios from 'axios';148 149console.log(axios.isCancel('something'));150````151 152If you use `require` for importing, **only default export is available**:153 154```js155const axios = require('axios');156 157console.log(axios.isCancel('something'));158```159 160For some bundlers and some ES6 linter's you may need to do the following:161 162```js163import { default as axios } from 'axios';164```165 166For cases where something went wrong when trying to import a module into a custom or legacy environment,167you can try importing the module package directly:168 169```js170const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)171// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)172```173 174### CDN175 176Using jsDelivr CDN (ES5 UMD browser module):177 178```html179<script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>180```181 182Using unpkg CDN:183 184```html185<script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>186```187 188## Example189 190> **Note**: CommonJS usage 191> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:192 193```js194import axios from 'axios';195//const axios = require('axios'); // legacy way196 197// Make a request for a user with a given ID198axios.get('/user?ID=12345')199 .then(function (response) {200 // handle success201 console.log(response);202 })203 .catch(function (error) {204 // handle error205 console.log(error);206 })207 .finally(function () {208 // always executed209 });210 211// Optionally the request above could also be done as212axios.get('/user', {213 params: {214 ID: 12345215 }216 })217 .then(function (response) {218 console.log(response);219 })220 .catch(function (error) {221 console.log(error);222 })223 .finally(function () {224 // always executed225 });226 227// Want to use async/await? Add the `async` keyword to your outer function/method.228async function getUser() {229 try {230 const response = await axios.get('/user?ID=12345');231 console.log(response);232 } catch (error) {233 console.error(error);234 }235}236```237 238> **Note**: `async/await` is part of ECMAScript 2017 and is not supported in Internet239> Explorer and older browsers, so use with caution.240 241Performing a `POST` request242 243```js244axios.post('/user', {245 firstName: 'Fred',246 lastName: 'Flintstone'247 })248 .then(function (response) {249 console.log(response);250 })251 .catch(function (error) {252 console.log(error);253 });254```255 256Performing multiple concurrent requests257 258```js259function getUserAccount() {260 return axios.get('/user/12345');261}262 263function getUserPermissions() {264 return axios.get('/user/12345/permissions');265}266 267Promise.all([getUserAccount(), getUserPermissions()])268 .then(function (results) {269 const acct = results[0];270 const perm = results[1];271 });272```273 274## axios API275 276Requests can be made by passing the relevant config to `axios`.277 278##### axios(config)279 280```js281// Send a POST request282axios({283 method: 'post',284 url: '/user/12345',285 data: {286 firstName: 'Fred',287 lastName: 'Flintstone'288 }289});290```291 292```js293// GET request for remote image in node.js294axios({295 method: 'get',296 url: 'https://bit.ly/2mTM3nY',297 responseType: 'stream'298})299 .then(function (response) {300 response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))301 });302```303 304##### axios(url[, config])305 306```js307// Send a GET request (default method)308axios('/user/12345');309```310 311### Request method aliases312 313For convenience, aliases have been provided for all common request methods.314 315##### axios.request(config)316##### axios.get(url[, config])317##### axios.delete(url[, config])318##### axios.head(url[, config])319##### axios.options(url[, config])320##### axios.post(url[, data[, config]])321##### axios.put(url[, data[, config]])322##### axios.patch(url[, data[, config]])323 324###### NOTE325When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.326 327### Concurrency (Deprecated)328Please use `Promise.all` to replace the below functions.329 330Helper functions for dealing with concurrent requests.331 332axios.all(iterable)333axios.spread(callback)334 335### Creating an instance336 337You can create a new instance of axios with a custom config.338 339##### axios.create([config])340 341```js342const instance = axios.create({343 baseURL: 'https://some-domain.com/api/',344 timeout: 1000,345 headers: {'X-Custom-Header': 'foobar'}346});347```348 349### Instance methods350 351The available instance methods are listed below. The specified config will be merged with the instance config.352 353##### axios#request(config)354##### axios#get(url[, config])355##### axios#delete(url[, config])356##### axios#head(url[, config])357##### axios#options(url[, config])358##### axios#post(url[, data[, config]])359##### axios#put(url[, data[, config]])360##### axios#patch(url[, data[, config]])361##### axios#getUri([config])362 363## Request Config364 365These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.366 367```js368{369 // `url` is the server URL that will be used for the request370 url: '/user',371 372 // `method` is the request method to be used when making the request373 method: 'get', // default374 375 // `baseURL` will be prepended to `url` unless `url` is absolute.376 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs377 // to methods of that instance.378 baseURL: 'https://some-domain.com/api/',379 380 // `transformRequest` allows changes to the request data before it is sent to the server381 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'382 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,383 // FormData or Stream384 // You may modify the headers object.385 transformRequest: [function (data, headers) {386 // Do whatever you want to transform the data387 388 return data;389 }],390 391 // `transformResponse` allows changes to the response data to be made before392 // it is passed to then/catch393 transformResponse: [function (data) {394 // Do whatever you want to transform the data395 396 return data;397 }],398 399 // `headers` are custom headers to be sent400 headers: {'X-Requested-With': 'XMLHttpRequest'},401 402 // `params` are the URL parameters to be sent with the request403 // Must be a plain object or a URLSearchParams object404 params: {405 ID: 12345406 },407 408 // `paramsSerializer` is an optional config that allows you to customize serializing `params`. 409 paramsSerializer: {410 411 //Custom encoder function which sends key/value pairs in an iterative fashion.412 encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, 413 414 // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.415 serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), 416 417 //Configuration for formatting array indexes in the params. 418 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). 419 },420 421 // `data` is the data to be sent as the request body422 // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'423 // When no `transformRequest` is set, must be of one of the following types:424 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams425 // - Browser only: FormData, File, Blob426 // - Node only: Stream, Buffer, FormData (form-data package)427 data: {428 firstName: 'Fred'429 },430 431 // syntax alternative to send data into the body432 // method post433 // only the value is sent, not the key434 data: 'Country=Brasil&City=Belo Horizonte',435 436 // `timeout` specifies the number of milliseconds before the request times out.437 // If the request takes longer than `timeout`, the request will be aborted.438 timeout: 1000, // default is `0` (no timeout)439 440 // `withCredentials` indicates whether or not cross-site Access-Control requests441 // should be made using credentials442 withCredentials: false, // default443 444 // `adapter` allows custom handling of requests which makes testing easier.445 // Return a promise and supply a valid response (see lib/adapters/README.md)446 adapter: function (config) {447 /* ... */448 },449 // Also, you can set the name of the built-in adapter, or provide an array with their names450 // to choose the first available in the environment451 adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch']452 453 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.454 // This will set an `Authorization` header, overwriting any existing455 // `Authorization` custom headers you have set using `headers`.456 // Please note that only HTTP Basic auth is configurable through this parameter.457 // For Bearer tokens and such, use `Authorization` custom headers instead.458 auth: {459 username: 'janedoe',460 password: 's00pers3cret'461 },462 463 // `responseType` indicates the type of data that the server will respond with464 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'465 // browser only: 'blob'466 responseType: 'json', // default467 468 // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)469 // Note: Ignored for `responseType` of 'stream' or client-side requests470 // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',471 // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',472 // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'473 responseEncoding: 'utf8', // default474 475 // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token476 xsrfCookieName: 'XSRF-TOKEN', // default477 478 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value479 xsrfHeaderName: 'X-XSRF-TOKEN', // default480 481 // `undefined` (default) - set XSRF header only for the same origin requests482 withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),483 484 // `onUploadProgress` allows handling of progress events for uploads485 // browser & node.js486 onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {487 // Do whatever you want with the Axios progress event488 },489 490 // `onDownloadProgress` allows handling of progress events for downloads491 // browser & node.js492 onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {493 // Do whatever you want with the Axios progress event494 },495 496 // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js497 maxContentLength: 2000,498 499 // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed500 maxBodyLength: 2000,501 502 // `validateStatus` defines whether to resolve or reject the promise for a given503 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`504 // or `undefined`), the promise will be resolved; otherwise, the promise will be505 // rejected.506 validateStatus: function (status) {507 return status >= 200 && status < 300; // default508 },509 510 // `maxRedirects` defines the maximum number of redirects to follow in node.js.511 // If set to 0, no redirects will be followed.512 maxRedirects: 21, // default513 514 // `beforeRedirect` defines a function that will be called before redirect.515 // Use this to adjust the request options upon redirecting,516 // to inspect the latest response headers,517 // or to cancel the request by throwing an error518 // If maxRedirects is set to 0, `beforeRedirect` is not used.519 beforeRedirect: (options, { headers }) => {520 if (options.hostname === "example.com") {521 options.auth = "user:password";522 }523 },524 525 // `socketPath` defines a UNIX Socket to be used in node.js.526 // e.g. '/var/run/docker.sock' to send requests to the docker daemon.527 // Only either `socketPath` or `proxy` can be specified.528 // If both are specified, `socketPath` is used.529 socketPath: null, // default530 531 // `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects.532 transport: undefined, // default533 534 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http535 // and https requests, respectively, in node.js. This allows options to be added like536 // `keepAlive` that are not enabled by default.537 httpAgent: new http.Agent({ keepAlive: true }),538 httpsAgent: new https.Agent({ keepAlive: true }),539 540 // `proxy` defines the hostname, port, and protocol of the proxy server.541 // You can also define your proxy using the conventional `http_proxy` and542 // `https_proxy` environment variables. If you are using environment variables543 // for your proxy configuration, you can also define a `no_proxy` environment544 // variable as a comma-separated list of domains that should not be proxied.545 // Use `false` to disable proxies, ignoring environment variables.546 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and547 // supplies credentials.548 // This will set an `Proxy-Authorization` header, overwriting any existing549 // `Proxy-Authorization` custom headers you have set using `headers`.550 // If the proxy server uses HTTPS, then you must set the protocol to `https`.551 proxy: {552 protocol: 'https',553 host: '127.0.0.1',554 // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined555 port: 9000,556 auth: {557 username: 'mikeymike',558 password: 'rapunz3l'559 }560 },561 562 // `cancelToken` specifies a cancel token that can be used to cancel the request563 // (see Cancellation section below for details)564 cancelToken: new CancelToken(function (cancel) {565 }),566 567 // an alternative way to cancel Axios requests using AbortController568 signal: new AbortController().signal,569 570 // `decompress` indicates whether or not the response body should be decompressed571 // automatically. If set to `true` will also remove the 'content-encoding' header572 // from the responses objects of all decompressed responses573 // - Node only (XHR cannot turn off decompression)574 decompress: true, // default575 576 // `insecureHTTPParser` boolean.577 // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.578 // This may allow interoperability with non-conformant HTTP implementations.579 // Using the insecure parser should be avoided.580 // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback581 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none582 insecureHTTPParser: undefined, // default583 584 // transitional options for backward compatibility that may be removed in the newer versions585 transitional: {586 // silent JSON parsing mode587 // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)588 // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')589 silentJSONParsing: true, // default value for the current Axios version590 591 // try to parse the response string as JSON even if `responseType` is not 'json'592 forcedJSONParsing: true,593 594 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts595 clarifyTimeoutError: false,596 },597 598 env: {599 // The FormData class to be used to automatically serialize the payload into a FormData object600 FormData: window?.FormData || global?.FormData601 },602 603 formSerializer: {604 visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values605 dots: boolean; // use dots instead of brackets format606 metaTokens: boolean; // keep special endings like {} in parameter key607 indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes608 },609 610 // http adapter only (node.js)611 maxRate: [612 100 * 1024, // 100KB/s upload limit,613 100 * 1024 // 100KB/s download limit614 ]615}616```617 618## Response Schema619 620The response for a request contains the following information.621 622```js623{624 // `data` is the response that was provided by the server625 data: {},626 627 // `status` is the HTTP status code from the server response628 status: 200,629 630 // `statusText` is the HTTP status message from the server response631 statusText: 'OK',632 633 // `headers` the HTTP headers that the server responded with634 // All header names are lowercase and can be accessed using the bracket notation.635 // Example: `response.headers['content-type']`636 headers: {},637 638 // `config` is the config that was provided to `axios` for the request639 config: {},640 641 // `request` is the request that generated this response642 // It is the last ClientRequest instance in node.js (in redirects)643 // and an XMLHttpRequest instance in the browser644 request: {}645}646```647 648When using `then`, you will receive the response as follows:649 650```js651axios.get('/user/12345')652 .then(function (response) {653 console.log(response.data);654 console.log(response.status);655 console.log(response.statusText);656 console.log(response.headers);657 console.log(response.config);658 });659```660 661When 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.662 663## Config Defaults664 665You can specify config defaults that will be applied to every request.666 667### Global axios defaults668 669```js670axios.defaults.baseURL = 'https://api.example.com';671 672// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.673// See below for an example using Custom instance defaults instead.674axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;675 676axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';677```678 679### Custom instance defaults680 681```js682// Set config defaults when creating the instance683const instance = axios.create({684 baseURL: 'https://api.example.com'685});686 687// Alter defaults after instance has been created688instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;689```690 691### Config order of precedence692 693Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults/index.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.694 695```js696// Create an instance using the config defaults provided by the library697// At this point the timeout config value is `0` as is the default for the library698const instance = axios.create();699 700// Override timeout default for the library701// Now all requests using this instance will wait 2.5 seconds before timing out702instance.defaults.timeout = 2500;703 704// Override timeout for this request as it's known to take a long time705instance.get('/longRequest', {706 timeout: 5000707});708```709 710## Interceptors711 712You can intercept requests or responses before they are handled by `then` or `catch`.713 714```js715// Add a request interceptor716axios.interceptors.request.use(function (config) {717 // Do something before request is sent718 return config;719 }, function (error) {720 // Do something with request error721 return Promise.reject(error);722 });723 724// Add a response interceptor725axios.interceptors.response.use(function (response) {726 // Any status code that lie within the range of 2xx cause this function to trigger727 // Do something with response data728 return response;729 }, function (error) {730 // Any status codes that falls outside the range of 2xx cause this function to trigger731 // Do something with response error732 return Promise.reject(error);733 });734```735 736If you need to remove an interceptor later you can.737 738```js739const myInterceptor = axios.interceptors.request.use(function () {/*...*/});740axios.interceptors.request.eject(myInterceptor);741```742 743You can also clear all interceptors for requests or responses.744```js745const instance = axios.create();746instance.interceptors.request.use(function () {/*...*/});747instance.interceptors.request.clear(); // Removes interceptors from requests748instance.interceptors.response.use(function () {/*...*/});749instance.interceptors.response.clear(); // Removes interceptors from responses750```751 752You can add interceptors to a custom instance of axios.753 754```js755const instance = axios.create();756instance.interceptors.request.use(function () {/*...*/});757```758 759When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay760in the execution of your axios request when the main thread is blocked (a promise is created under the hood for761the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag762to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.763 764```js765axios.interceptors.request.use(function (config) {766 config.headers.test = 'I am only a header!';767 return config;768}, null, { synchronous: true });769```770 771If you want to execute a particular interceptor based on a runtime check,772you can add a `runWhen` function to the options object. The request interceptor will not be executed **if and only if** the return773of `runWhen` is `false`. The function will be called with the config774object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an775asynchronous request interceptor that only needs to run at certain times.776 777```js778function onGetCall(config) {779 return config.method === 'get';780}781axios.interceptors.request.use(function (config) {782 config.headers.test = 'special get headers';783 return config;784}, null, { runWhen: onGetCall });785```786 787> **Note:** options parameter(having `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment.788 789### Multiple Interceptors790 791Given you add multiple response interceptors792and when the response was fulfilled793- then each interceptor is executed794- then they are executed in the order they were added795- then only the last interceptor's result is returned796- then every interceptor receives the result of its predecessor797- and when the fulfillment-interceptor throws798 - then the following fulfillment-interceptor is not called799 - then the following rejection-interceptor is called800 - once caught, another following fulfill-interceptor is called again (just like in a promise chain).801 802Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.803 804## Error Types805 806There 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.807 808The general structure of axios errors is as follows:809| Property | Definition |810| -------- | ---------- |811| message | A quick summary of the error message and the status it failed with. |812| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. |813| stack | Provides the stack trace of the error. | 814| config | An axios config object with specific instance configurations defined by the user from when the request was made |815| code | Represents an axios identified error. The table below lists out specific definitions for internal axios error. |816| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings. 817 818Below is a list of potential axios identified error819| Code | Definition |820| -------- | ---------- |821| ERR_BAD_OPTION_VALUE | Invalid or unsupported value provided in axios configuration. |822| ERR_BAD_OPTION | Invalid option provided in axios configuration. |823| ECONNABORTED | Request timed out due to exceeding timeout specified in axios configuration. |824| ETIMEDOUT | Request timed out due to exceeding default axios timelimit. |825| ERR_NETWORK | Network-related issue.826| ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration.827| ERR_DEPRECATED | Deprecated feature or method used in axios. 828| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. 829| ERR_BAD_REQUEST | Requested has unexpected format or missing required parameters. |830| ERR_CANCELED | Feature or method is canceled explicitly by the user. 831| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. 832| ERR_INVALID_URL | Invalid URL provided for axios request.833 834## Handling Errors835 836the 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.837 838```js839axios.get('/user/12345')840 .catch(function (error) {841 if (error.response) {842 // The request was made and the server responded with a status code843 // that falls out of the range of 2xx844 console.log(error.response.data);845 console.log(error.response.status);846 console.log(error.response.headers);847 } else if (error.request) {848 // The request was made but no response was received849 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of850 // http.ClientRequest in node.js851 console.log(error.request);852 } else {853 // Something happened in setting up the request that triggered an Error854 console.log('Error', error.message);855 }856 console.log(error.config);857 });858```859 860Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.861 862```js863axios.get('/user/12345', {864 validateStatus: function (status) {865 return status < 500; // Resolve only if the status code is less than 500866 }867})868```869 870Using `toJSON` you get an object with more information about the HTTP error.871 872```js873axios.get('/user/12345')874 .catch(function (error) {875 console.log(error.toJSON());876 });877```878 879## Cancellation880 881### AbortController882 883Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:884 885```js886const controller = new AbortController();887 888axios.get('/foo/bar', {889 signal: controller.signal890}).then(function(response) {891 //...892});893// cancel the request894controller.abort()895```896 897### CancelToken `πdeprecated`898 899You can also cancel a request using a *CancelToken*.900 901> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).902 903> This API is deprecated since v0.22.0 and shouldn't be used in new projects904 905You can create a cancel token using the `CancelToken.source` factory as shown below:906 907```js908const CancelToken = axios.CancelToken;909const source = CancelToken.source();910 911axios.get('/user/12345', {912 cancelToken: source.token913}).catch(function (thrown) {914 if (axios.isCancel(thrown)) {915 console.log('Request canceled', thrown.message);916 } else {917 // handle error918 }919});920 921axios.post('/user/12345', {922 name: 'new name'923}, {924 cancelToken: source.token925})926 927// cancel the request (the message parameter is optional)928source.cancel('Operation canceled by the user.');929```930 931You can also create a cancel token by passing an executor function to the `CancelToken` constructor:932 933```js934const CancelToken = axios.CancelToken;935let cancel;936 937axios.get('/user/12345', {938 cancelToken: new CancelToken(function executor(c) {939 // An executor function receives a cancel function as a parameter940 cancel = c;941 })942});943 944// cancel the request945cancel();946```947 948> **Note:** you can cancel several requests with the same cancel token/abort controller.949> 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.950 951> During the transition period, you can use both cancellation APIs, even for the same request:952 953## Using `application/x-www-form-urlencoded` format954 955### URLSearchParams956 957By 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).958 959```js960const params = new URLSearchParams({ foo: 'bar' });961params.append('extraparam', 'value');962axios.post('/foo', params);963```964 965### Query string (Older browsers)966 967For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).968 969Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:970 971```js972const qs = require('qs');973axios.post('/foo', qs.stringify({ 'bar': 123 }));974```975 976Or in another way (ES6),977 978```js979import qs from 'qs';980const data = { 'bar': 123 };981const options = {982 method: 'POST',983 headers: { 'content-type': 'application/x-www-form-urlencoded' },984 data: qs.stringify(data),985 url,986};987axios(options);988```989 990### Older Node.js versions991 992For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:993 994```js995const querystring = require('querystring');996axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));997```998 999You can also use the [`qs`](https://github.com/ljharb/qs) library.1000 1001> **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.1002 1003### π Automatic serialization to URLSearchParams1004 1005Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".1006 1007```js1008const data = {1009 x: 1,1010 arr: [1, 2, 3],1011 arr2: [1, [2], 3],1012 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],1013};1014 1015await axios.postForm('https://postman-echo.com/post', data,1016 {headers: {'content-type': 'application/x-www-form-urlencoded'}}1017);1018```1019 1020The server will handle it as:1021 1022```js1023 {1024 x: '1',1025 'arr[]': [ '1', '2', '3' ],1026 'arr2[0]': '1',1027 'arr2[1][0]': '2',1028 'arr2[2]': '3',1029 'arr3[]': [ '1', '2', '3' ],1030 'users[0][name]': 'Peter',1031 'users[0][surname]': 'griffin',1032 'users[1][name]': 'Thomas',1033 'users[1][surname]': 'Anderson'1034 }1035````1036 1037If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically1038 1039```js1040 var app = express();1041 1042 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies1043 1044 app.post('/', function (req, res, next) {1045 // echo body as JSON1046 res.send(JSON.stringify(req.body));1047 });1048 1049 server = app.listen(3000);1050```1051 1052## Using `multipart/form-data` format1053 1054### FormData1055 1056To send the data as a `multipart/formdata` you need to pass a formData instance as a payload.1057Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.1058 1059```js1060const formData = new FormData();1061formData.append('foo', 'bar');1062 1063axios.post('https://httpbin.org/post', formData);1064```1065 1066In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:1067 1068```js1069const FormData = require('form-data');1070 1071const form = new FormData();1072form.append('my_field', 'my value');1073form.append('my_buffer', new Buffer(10));1074form.append('my_file', fs.createReadStream('/foo/bar.jpg'));1075 1076axios.post('https://example.com', form)1077```1078 1079### π Automatic serialization to FormData1080 1081Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`1082header is set to `multipart/form-data`.1083 1084The following request will submit the data in a FormData format (Browser & Node.js):1085 1086```js1087import axios from 'axios';1088 1089axios.post('https://httpbin.org/post', {x: 1}, {1090 headers: {1091 'Content-Type': 'multipart/form-data'1092 }1093}).then(({data}) => console.log(data));1094```1095 1096In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.1097 1098You can overload the FormData class by setting the `env.FormData` config variable,1099but you probably won't need it in most cases:1100 1101```js1102const axios = require('axios');1103var FormData = require('form-data');1104 1105axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {1106 headers: {1107 'Content-Type': 'multipart/form-data'1108 }1109}).then(({data}) => console.log(data));1110```1111 1112Axios FormData serializer supports some special endings to perform the following operations:1113 1114- `{}` - serialize the value with JSON.stringify1115- `[]` - unwrap the array-like object as separate fields with the same key1116 1117> **Note**: unwrap/expand operation will be used by default on arrays and FileList objects1118 1119FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:1120 1121- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object1122to a `FormData` object by following custom rules.1123 1124- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;1125 1126- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.1127The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.1128 1129- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects1130 1131 - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)1132 - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)1133 - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)1134 1135Let's say we have an object like this one:1136 1137```js1138const obj = {1139 x: 1,1140 arr: [1, 2, 3],1141 arr2: [1, [2], 3],1142 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],1143 'obj2{}': [{x:1}]1144};1145```1146 1147The following steps will be executed by the Axios serializer internally:1148 1149```js1150const formData = new FormData();1151formData.append('x', '1');1152formData.append('arr[]', '1');1153formData.append('arr[]', '2');1154formData.append('arr[]', '3');1155formData.append('arr2[0]', '1');1156formData.append('arr2[1][0]', '2');1157formData.append('arr2[2]', '3');1158formData.append('users[0][name]', 'Peter');1159formData.append('users[0][surname]', 'Griffin');1160formData.append('users[1][name]', 'Thomas');1161formData.append('users[1][surname]', 'Anderson');1162formData.append('obj2{}', '[{"x":1}]');1163```1164 1165Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`1166which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.1167 1168## Files Posting1169 1170You can easily submit a single file:1171 1172```js1173await axios.postForm('https://httpbin.org/post', {1174 'myVar' : 'foo',1175 'file': document.querySelector('#fileInput').files[0]1176});1177```1178 1179or multiple files as `multipart/form-data`:1180 1181```js1182await axios.postForm('https://httpbin.org/post', {1183 'files[]': document.querySelector('#fileInput').files1184});1185```1186 1187`FileList` object can be passed directly:1188 1189```js1190await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)1191```1192 1193All files will be sent with the same field names: `files[]`.1194 1195## π HTML Form Posting (browser)1196 1197Pass HTML Form element as a payload to submit it as `multipart/form-data` content.1198 1199```js1200await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));