codekingpro/portable-devtools
115k
1<h3 align="center">2 Platinum sponsors3 <br>4</h3>5 6<div align="center">7 <a href="https://runalloy.com?utm_source=github&utm_medium=referral&utm_campaign=121423_axios">8 <picture>9 <source width="400px" media="(prefers-color-scheme: dark)" srcset="https://github.com/axios/axios/assets/4814473/f6067247-7eba-4069-852a-ab1bb85b1780">10 <source width="400px" media="(prefers-color-scheme: light)" srcset="https://github.com/axios/axios/assets/4814473/75c37f4d-36e6-44f5-a068-3edd77c00a10">11 <img width="400px" src="https://github.com/axios/axios/assets/4814473/75c37f4d-36e6-44f5-a068-3edd77c00a10" />12 </picture>13 </a>14 15 <p align="center">Alloy is the integration development platform that makes it simple and <br>fast for SaaS companies to launch critical user-facing integrations.</p>16 <p align="center">17 <a href="https://runalloy.com/signup?utm_source=github&utm_medium=referral&utm_campaign=11823_axios"><b>Sign up free</b></a> โข18 <a href="https://docs.runalloy.com/docs?utm_source=github&utm_medium=referral&utm_campaign=11823_axios"><b>Documentation</b></a>19 </p>20 <br><br>21</div>22 23<h3 align="center">24 Gold sponsors25 <br><br>26</h3>27 28<div align="center">29 <a href="https://stytch.com?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_content=logo&utm_campaign=axios-http">30 <picture>31 <source width="200px" media="(prefers-color-scheme: dark)" srcset="https://github.com/axios/axios/assets/4814473/538d715a-13c7-4668-ae7d-37a4548423f4">32 <source width="200px" media="(prefers-color-scheme: light)" srcset="https://github.com/axios/axios/assets/4814473/b6a9a7bc-9fb1-4b9b-909f-1b4bee1fd142">33 <img width="200px" src="https://github.com/axios/axios/assets/4814473/b6a9a7bc-9fb1-4b9b-909f-1b4bee1fd142" />34 </picture>35 </a>36 <p align="center">API-first authentication, authorization, and fraud prevention</p>37 <p align="center">38 <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> โข39 <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 Backend SDK</b></a>40 </p>41</div>42 43 44<br><br>45<div align="center">46 <a href="https://axios-http.com"><img src="https://axios-http.com/assets/logo.svg" /></a><br>47</div>48 49<p align="center">Promise based HTTP client for the browser and node.js</p>50 51<p align="center">52 <a href="https://axios-http.com/"><b>Website</b></a> โข53 <a href="https://axios-http.com/docs/intro"><b>Documentation</b></a>54</p>55 56<div align="center">57 58[](https://www.npmjs.org/package/axios)59[](https://cdnjs.com/libraries/axios)60[](https://github.com/axios/axios/actions/workflows/ci.yml)61[](https://gitpod.io/#https://github.com/axios/axios)62[](https://coveralls.io/r/mzabriskie/axios)63[](https://packagephobia.now.sh/result?p=axios)64[](https://bundlephobia.com/package/axios@latest)65[](https://npm-stat.com/charts.html?package=axios)66[](https://gitter.im/mzabriskie/axios)67[](https://www.codetriage.com/axios/axios)68[](https://snyk.io/test/npm/axios)69 70 71 72 73</div>74 75## Table of Contents76 77 - [Features](#features)78 - [Browser Support](#browser-support)79 - [Installing](#installing)80 - [Package manager](#package-manager)81 - [CDN](#cdn)82 - [Example](#example)83 - [Axios API](#axios-api)84 - [Request method aliases](#request-method-aliases)85 - [Concurrency ๐](#concurrency-deprecated)86 - [Creating an instance](#creating-an-instance)87 - [Instance methods](#instance-methods)88 - [Request Config](#request-config)89 - [Response Schema](#response-schema)90 - [Config Defaults](#config-defaults)91 - [Global axios defaults](#global-axios-defaults)92 - [Custom instance defaults](#custom-instance-defaults)93 - [Config order of precedence](#config-order-of-precedence)94 - [Interceptors](#interceptors)95 - [Multiple Interceptors](#multiple-interceptors)96 - [Handling Errors](#handling-errors)97 - [Cancellation](#cancellation)98 - [AbortController](#abortcontroller)99 - [CancelToken ๐](#canceltoken-deprecated)100 - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)101 - [URLSearchParams](#urlsearchparams)102 - [Query string](#query-string-older-browsers)103 - [๐ Automatic serialization](#-automatic-serialization-to-urlsearchparams)104 - [Using multipart/form-data format](#using-multipartform-data-format)105 - [FormData](#formdata)106 - [๐ Automatic serialization](#-automatic-serialization-to-formdata)107 - [Files Posting](#files-posting)108 - [HTML Form Posting](#-html-form-posting-browser)109 - [๐ Progress capturing](#-progress-capturing)110 - [๐ Rate limiting](#-progress-capturing)111 - [๐ AxiosHeaders](#-axiosheaders)112 - [Semver](#semver)113 - [Promises](#promises)114 - [TypeScript](#typescript)115 - [Resources](#resources)116 - [Credits](#credits)117 - [License](#license)118 119## Features120 121- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser122- Make [http](https://nodejs.org/api/http.html) requests from node.js123- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API124- Intercept request and response125- Transform request and response data126- Cancel requests127- Automatic transforms for [JSON](https://www.json.org/json-en.html) data128- ๐ Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings129- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)130 131## Browser Support132 133 |  |  |  |  |  |134--- | --- | --- | --- | --- | --- |135Latest โ | Latest โ | Latest โ | Latest โ | Latest โ | 11 โ |136 137[](https://saucelabs.com/u/axios)138 139## Installing140 141### Package manager142 143Using npm:144 145```bash146$ npm install axios147```148 149Using bower:150 151```bash152$ bower install axios153```154 155Using yarn:156 157```bash158$ yarn add axios159```160 161Using pnpm:162 163```bash164$ pnpm add axios165```166 167Once the package is installed, you can import the library using `import` or `require` approach:168 169```js170import axios, {isCancel, AxiosError} from 'axios';171```172 173You can also use the default export, since the named export is just a re-export from the Axios factory:174 175```js176import axios from 'axios';177 178console.log(axios.isCancel('something'));179````180 181If you use `require` for importing, **only default export is available**:182 183```js184const axios = require('axios');185 186console.log(axios.isCancel('something'));187```188 189For cases where something went wrong when trying to import a module into a custom or legacy environment,190you can try importing the module package directly:191 192```js193const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)194// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)195```196 197### CDN198 199Using jsDelivr CDN (ES5 UMD browser module):200 201```html202<script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>203```204 205Using unpkg CDN:206 207```html208<script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>209```210 211## Example212 213> **Note**: CommonJS usage 214> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:215 216```js217import axios from 'axios';218//const axios = require('axios'); // legacy way219 220// Make a request for a user with a given ID221axios.get('/user?ID=12345')222 .then(function (response) {223 // handle success224 console.log(response);225 })226 .catch(function (error) {227 // handle error228 console.log(error);229 })230 .finally(function () {231 // always executed232 });233 234// Optionally the request above could also be done as235axios.get('/user', {236 params: {237 ID: 12345238 }239 })240 .then(function (response) {241 console.log(response);242 })243 .catch(function (error) {244 console.log(error);245 })246 .finally(function () {247 // always executed248 });249 250// Want to use async/await? Add the `async` keyword to your outer function/method.251async function getUser() {252 try {253 const response = await axios.get('/user?ID=12345');254 console.log(response);255 } catch (error) {256 console.error(error);257 }258}259```260 261> **Note**: `async/await` is part of ECMAScript 2017 and is not supported in Internet262> Explorer and older browsers, so use with caution.263 264Performing a `POST` request265 266```js267axios.post('/user', {268 firstName: 'Fred',269 lastName: 'Flintstone'270 })271 .then(function (response) {272 console.log(response);273 })274 .catch(function (error) {275 console.log(error);276 });277```278 279Performing multiple concurrent requests280 281```js282function getUserAccount() {283 return axios.get('/user/12345');284}285 286function getUserPermissions() {287 return axios.get('/user/12345/permissions');288}289 290Promise.all([getUserAccount(), getUserPermissions()])291 .then(function (results) {292 const acct = results[0];293 const perm = results[1];294 });295```296 297## axios API298 299Requests can be made by passing the relevant config to `axios`.300 301##### axios(config)302 303```js304// Send a POST request305axios({306 method: 'post',307 url: '/user/12345',308 data: {309 firstName: 'Fred',310 lastName: 'Flintstone'311 }312});313```314 315```js316// GET request for remote image in node.js317axios({318 method: 'get',319 url: 'https://bit.ly/2mTM3nY',320 responseType: 'stream'321})322 .then(function (response) {323 response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))324 });325```326 327##### axios(url[, config])328 329```js330// Send a GET request (default method)331axios('/user/12345');332```333 334### Request method aliases335 336For convenience, aliases have been provided for all common request methods.337 338##### axios.request(config)339##### axios.get(url[, config])340##### axios.delete(url[, config])341##### axios.head(url[, config])342##### axios.options(url[, config])343##### axios.post(url[, data[, config]])344##### axios.put(url[, data[, config]])345##### axios.patch(url[, data[, config]])346 347###### NOTE348When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.349 350### Concurrency (Deprecated)351Please use `Promise.all` to replace the below functions.352 353Helper functions for dealing with concurrent requests.354 355axios.all(iterable)356axios.spread(callback)357 358### Creating an instance359 360You can create a new instance of axios with a custom config.361 362##### axios.create([config])363 364```js365const instance = axios.create({366 baseURL: 'https://some-domain.com/api/',367 timeout: 1000,368 headers: {'X-Custom-Header': 'foobar'}369});370```371 372### Instance methods373 374The available instance methods are listed below. The specified config will be merged with the instance config.375 376##### axios#request(config)377##### axios#get(url[, config])378##### axios#delete(url[, config])379##### axios#head(url[, config])380##### axios#options(url[, config])381##### axios#post(url[, data[, config]])382##### axios#put(url[, data[, config]])383##### axios#patch(url[, data[, config]])384##### axios#getUri([config])385 386## Request Config387 388These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.389 390```js391{392 // `url` is the server URL that will be used for the request393 url: '/user',394 395 // `method` is the request method to be used when making the request396 method: 'get', // default397 398 // `baseURL` will be prepended to `url` unless `url` is absolute.399 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs400 // to methods of that instance.401 baseURL: 'https://some-domain.com/api/',402 403 // `transformRequest` allows changes to the request data before it is sent to the server404 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'405 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,406 // FormData or Stream407 // You may modify the headers object.408 transformRequest: [function (data, headers) {409 // Do whatever you want to transform the data410 411 return data;412 }],413 414 // `transformResponse` allows changes to the response data to be made before415 // it is passed to then/catch416 transformResponse: [function (data) {417 // Do whatever you want to transform the data418 419 return data;420 }],421 422 // `headers` are custom headers to be sent423 headers: {'X-Requested-With': 'XMLHttpRequest'},424 425 // `params` are the URL parameters to be sent with the request426 // Must be a plain object or a URLSearchParams object427 params: {428 ID: 12345429 },430 431 // `paramsSerializer` is an optional config that allows you to customize serializing `params`. 432 paramsSerializer: {433 434 //Custom encoder function which sends key/value pairs in an iterative fashion.435 encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, 436 437 // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.438 serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), 439 440 //Configuration for formatting array indexes in the params. 441 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). 442 },443 444 // `data` is the data to be sent as the request body445 // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'446 // When no `transformRequest` is set, must be of one of the following types:447 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams448 // - Browser only: FormData, File, Blob449 // - Node only: Stream, Buffer, FormData (form-data package)450 data: {451 firstName: 'Fred'452 },453 454 // syntax alternative to send data into the body455 // method post456 // only the value is sent, not the key457 data: 'Country=Brasil&City=Belo Horizonte',458 459 // `timeout` specifies the number of milliseconds before the request times out.460 // If the request takes longer than `timeout`, the request will be aborted.461 timeout: 1000, // default is `0` (no timeout)462 463 // `withCredentials` indicates whether or not cross-site Access-Control requests464 // should be made using credentials465 withCredentials: false, // default466 467 // `adapter` allows custom handling of requests which makes testing easier.468 // Return a promise and supply a valid response (see lib/adapters/README.md).469 adapter: function (config) {470 /* ... */471 },472 473 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.474 // This will set an `Authorization` header, overwriting any existing475 // `Authorization` custom headers you have set using `headers`.476 // Please note that only HTTP Basic auth is configurable through this parameter.477 // For Bearer tokens and such, use `Authorization` custom headers instead.478 auth: {479 username: 'janedoe',480 password: 's00pers3cret'481 },482 483 // `responseType` indicates the type of data that the server will respond with484 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'485 // browser only: 'blob'486 responseType: 'json', // default487 488 // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)489 // Note: Ignored for `responseType` of 'stream' or client-side requests490 // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',491 // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',492 // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'493 responseEncoding: 'utf8', // default494 495 // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token496 xsrfCookieName: 'XSRF-TOKEN', // default497 498 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value499 xsrfHeaderName: 'X-XSRF-TOKEN', // default500 501 // `undefined` (default) - set XSRF header only for the same origin requests502 withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),503 504 // `onUploadProgress` allows handling of progress events for uploads505 // browser & node.js506 onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {507 // Do whatever you want with the Axios progress event508 },509 510 // `onDownloadProgress` allows handling of progress events for downloads511 // browser & node.js512 onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {513 // Do whatever you want with the Axios progress event514 },515 516 // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js517 maxContentLength: 2000,518 519 // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed520 maxBodyLength: 2000,521 522 // `validateStatus` defines whether to resolve or reject the promise for a given523 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`524 // or `undefined`), the promise will be resolved; otherwise, the promise will be525 // rejected.526 validateStatus: function (status) {527 return status >= 200 && status < 300; // default528 },529 530 // `maxRedirects` defines the maximum number of redirects to follow in node.js.531 // If set to 0, no redirects will be followed.532 maxRedirects: 21, // default533 534 // `beforeRedirect` defines a function that will be called before redirect.535 // Use this to adjust the request options upon redirecting,536 // to inspect the latest response headers,537 // or to cancel the request by throwing an error538 // If maxRedirects is set to 0, `beforeRedirect` is not used.539 beforeRedirect: (options, { headers }) => {540 if (options.hostname === "example.com") {541 options.auth = "user:password";542 }543 },544 545 // `socketPath` defines a UNIX Socket to be used in node.js.546 // e.g. '/var/run/docker.sock' to send requests to the docker daemon.547 // Only either `socketPath` or `proxy` can be specified.548 // If both are specified, `socketPath` is used.549 socketPath: null, // default550 551 // `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.552 transport: undefined, // default553 554 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http555 // and https requests, respectively, in node.js. This allows options to be added like556 // `keepAlive` that are not enabled by default.557 httpAgent: new http.Agent({ keepAlive: true }),558 httpsAgent: new https.Agent({ keepAlive: true }),559 560 // `proxy` defines the hostname, port, and protocol of the proxy server.561 // You can also define your proxy using the conventional `http_proxy` and562 // `https_proxy` environment variables. If you are using environment variables563 // for your proxy configuration, you can also define a `no_proxy` environment564 // variable as a comma-separated list of domains that should not be proxied.565 // Use `false` to disable proxies, ignoring environment variables.566 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and567 // supplies credentials.568 // This will set an `Proxy-Authorization` header, overwriting any existing569 // `Proxy-Authorization` custom headers you have set using `headers`.570 // If the proxy server uses HTTPS, then you must set the protocol to `https`.571 proxy: {572 protocol: 'https',573 host: '127.0.0.1',574 // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined575 port: 9000,576 auth: {577 username: 'mikeymike',578 password: 'rapunz3l'579 }580 },581 582 // `cancelToken` specifies a cancel token that can be used to cancel the request583 // (see Cancellation section below for details)584 cancelToken: new CancelToken(function (cancel) {585 }),586 587 // an alternative way to cancel Axios requests using AbortController588 signal: new AbortController().signal,589 590 // `decompress` indicates whether or not the response body should be decompressed591 // automatically. If set to `true` will also remove the 'content-encoding' header592 // from the responses objects of all decompressed responses593 // - Node only (XHR cannot turn off decompression)594 decompress: true, // default595 596 // `insecureHTTPParser` boolean.597 // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.598 // This may allow interoperability with non-conformant HTTP implementations.599 // Using the insecure parser should be avoided.600 // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback601 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none602 insecureHTTPParser: undefined, // default603 604 // transitional options for backward compatibility that may be removed in the newer versions605 transitional: {606 // silent JSON parsing mode607 // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)608 // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')609 silentJSONParsing: true, // default value for the current Axios version610 611 // try to parse the response string as JSON even if `responseType` is not 'json'612 forcedJSONParsing: true,613 614 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts615 clarifyTimeoutError: false,616 },617 618 env: {619 // The FormData class to be used to automatically serialize the payload into a FormData object620 FormData: window?.FormData || global?.FormData621 },622 623 formSerializer: {624 visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values625 dots: boolean; // use dots instead of brackets format626 metaTokens: boolean; // keep special endings like {} in parameter key627 indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes628 },629 630 // http adapter only (node.js)631 maxRate: [632 100 * 1024, // 100KB/s upload limit,633 100 * 1024 // 100KB/s download limit634 ]635}636```637 638## Response Schema639 640The response for a request contains the following information.641 642```js643{644 // `data` is the response that was provided by the server645 data: {},646 647 // `status` is the HTTP status code from the server response648 status: 200,649 650 // `statusText` is the HTTP status message from the server response651 statusText: 'OK',652 653 // `headers` the HTTP headers that the server responded with654 // All header names are lowercase and can be accessed using the bracket notation.655 // Example: `response.headers['content-type']`656 headers: {},657 658 // `config` is the config that was provided to `axios` for the request659 config: {},660 661 // `request` is the request that generated this response662 // It is the last ClientRequest instance in node.js (in redirects)663 // and an XMLHttpRequest instance in the browser664 request: {}665}666```667 668When using `then`, you will receive the response as follows:669 670```js671axios.get('/user/12345')672 .then(function (response) {673 console.log(response.data);674 console.log(response.status);675 console.log(response.statusText);676 console.log(response.headers);677 console.log(response.config);678 });679```680 681When 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.682 683## Config Defaults684 685You can specify config defaults that will be applied to every request.686 687### Global axios defaults688 689```js690axios.defaults.baseURL = 'https://api.example.com';691 692// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.693// See below for an example using Custom instance defaults instead.694axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;695 696axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';697```698 699### Custom instance defaults700 701```js702// Set config defaults when creating the instance703const instance = axios.create({704 baseURL: 'https://api.example.com'705});706 707// Alter defaults after instance has been created708instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;709```710 711### Config order of precedence712 713Config 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.714 715```js716// Create an instance using the config defaults provided by the library717// At this point the timeout config value is `0` as is the default for the library718const instance = axios.create();719 720// Override timeout default for the library721// Now all requests using this instance will wait 2.5 seconds before timing out722instance.defaults.timeout = 2500;723 724// Override timeout for this request as it's known to take a long time725instance.get('/longRequest', {726 timeout: 5000727});728```729 730## Interceptors731 732You can intercept requests or responses before they are handled by `then` or `catch`.733 734```js735// Add a request interceptor736axios.interceptors.request.use(function (config) {737 // Do something before request is sent738 return config;739 }, function (error) {740 // Do something with request error741 return Promise.reject(error);742 });743 744// Add a response interceptor745axios.interceptors.response.use(function (response) {746 // Any status code that lie within the range of 2xx cause this function to trigger747 // Do something with response data748 return response;749 }, function (error) {750 // Any status codes that falls outside the range of 2xx cause this function to trigger751 // Do something with response error752 return Promise.reject(error);753 });754```755 756If you need to remove an interceptor later you can.757 758```js759const myInterceptor = axios.interceptors.request.use(function () {/*...*/});760axios.interceptors.request.eject(myInterceptor);761```762 763You can also clear all interceptors for requests or responses.764```js765const instance = axios.create();766instance.interceptors.request.use(function () {/*...*/});767instance.interceptors.request.clear(); // Removes interceptors from requests768instance.interceptors.response.use(function () {/*...*/});769instance.interceptors.response.clear(); // Removes interceptors from responses770```771 772You can add interceptors to a custom instance of axios.773 774```js775const instance = axios.create();776instance.interceptors.request.use(function () {/*...*/});777```778 779When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay780in the execution of your axios request when the main thread is blocked (a promise is created under the hood for781the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag782to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.783 784```js785axios.interceptors.request.use(function (config) {786 config.headers.test = 'I am only a header!';787 return config;788}, null, { synchronous: true });789```790 791If you want to execute a particular interceptor based on a runtime check,792you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return793of `runWhen` is `false`. The function will be called with the config794object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an795asynchronous request interceptor that only needs to run at certain times.796 797```js798function onGetCall(config) {799 return config.method === 'get';800}801axios.interceptors.request.use(function (config) {802 config.headers.test = 'special get headers';803 return config;804}, null, { runWhen: onGetCall });805```806 807### Multiple Interceptors808 809Given you add multiple response interceptors810and when the response was fulfilled811- then each interceptor is executed812- then they are executed in the order they were added813- then only the last interceptor's result is returned814- then every interceptor receives the result of its predecessor815- and when the fulfillment-interceptor throws816 - then the following fulfillment-interceptor is not called817 - then the following rejection-interceptor is called818 - once caught, another following fulfill-interceptor is called again (just like in a promise chain).819 820Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.821 822## Error Types823 824There 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.825 826The general structure of axios errors is as follows:827| Property | Definition |828| -------- | ---------- |829| message | A quick summary of the error message and the status it failed with. |830| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. |831| stack | Provides the stack trace of the error. | 832| config | An axios config object with specific instance configurations defined by the user from when the request was made |833| code | Represents an axios identified error. The table below lists out specific definitions for internal axios error. |834| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings. 835 836Below is a list of potential axios identified error837| Code | Definition |838| -------- | ---------- |839| ERR_BAD_OPTION_VALUE | Invalid or unsupported value provided in axios configuration. |840| ERR_BAD_OPTION | Invalid option provided in axios configuration. |841| ECONNABORTED | Request timed out due to exceeding timeout specified in axios configuration. |842| ETIMEDOUT | Request timed out due to exceeding default axios timelimit. |843| ERR_NETWORK | Network-related issue.844| ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration.845| ERR_DEPRECATED | Deprecated feature or method used in axios. 846| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. 847| ERR_BAD_REQUEST | Requested has unexpected format or missing required parameters. |848| ERR_CANCELED | Feature or method is canceled explicitly by the user. 849| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. 850| ERR_INVALID_URL | Invalid URL provided for axios request.851 852## Handling Errors853 854the 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.855 856```js857axios.get('/user/12345')858 .catch(function (error) {859 if (error.response) {860 // The request was made and the server responded with a status code861 // that falls out of the range of 2xx862 console.log(error.response.data);863 console.log(error.response.status);864 console.log(error.response.headers);865 } else if (error.request) {866 // The request was made but no response was received867 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of868 // http.ClientRequest in node.js869 console.log(error.request);870 } else {871 // Something happened in setting up the request that triggered an Error872 console.log('Error', error.message);873 }874 console.log(error.config);875 });876```877 878Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.879 880```js881axios.get('/user/12345', {882 validateStatus: function (status) {883 return status < 500; // Resolve only if the status code is less than 500884 }885})886```887 888Using `toJSON` you get an object with more information about the HTTP error.889 890```js891axios.get('/user/12345')892 .catch(function (error) {893 console.log(error.toJSON());894 });895```896 897## Cancellation898 899### AbortController900 901Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:902 903```js904const controller = new AbortController();905 906axios.get('/foo/bar', {907 signal: controller.signal908}).then(function(response) {909 //...910});911// cancel the request912controller.abort()913```914 915### CancelToken `๐deprecated`916 917You can also cancel a request using a *CancelToken*.918 919> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).920 921> This API is deprecated since v0.22.0 and shouldn't be used in new projects922 923You can create a cancel token using the `CancelToken.source` factory as shown below:924 925```js926const CancelToken = axios.CancelToken;927const source = CancelToken.source();928 929axios.get('/user/12345', {930 cancelToken: source.token931}).catch(function (thrown) {932 if (axios.isCancel(thrown)) {933 console.log('Request canceled', thrown.message);934 } else {935 // handle error936 }937});938 939axios.post('/user/12345', {940 name: 'new name'941}, {942 cancelToken: source.token943})944 945// cancel the request (the message parameter is optional)946source.cancel('Operation canceled by the user.');947```948 949You can also create a cancel token by passing an executor function to the `CancelToken` constructor:950 951```js952const CancelToken = axios.CancelToken;953let cancel;954 955axios.get('/user/12345', {956 cancelToken: new CancelToken(function executor(c) {957 // An executor function receives a cancel function as a parameter958 cancel = c;959 })960});961 962// cancel the request963cancel();964```965 966> **Note:** you can cancel several requests with the same cancel token/abort controller.967> 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.968 969> During the transition period, you can use both cancellation APIs, even for the same request:970 971## Using `application/x-www-form-urlencoded` format972 973### URLSearchParams974 975By 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).976 977```js978const params = new URLSearchParams({ foo: 'bar' });979params.append('extraparam', 'value');980axios.post('/foo', params);981```982 983### Query string (Older browsers)984 985For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).986 987Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:988 989```js990const qs = require('qs');991axios.post('/foo', qs.stringify({ 'bar': 123 }));992```993 994Or in another way (ES6),995 996```js997import qs from 'qs';998const data = { 'bar': 123 };999const options = {1000 method: 'POST',1001 headers: { 'content-type': 'application/x-www-form-urlencoded' },1002 data: qs.stringify(data),1003 url,1004};1005axios(options);1006```1007 1008### Older Node.js versions1009 1010For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:1011 1012```js1013const querystring = require('querystring');1014axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));1015```1016 1017You can also use the [`qs`](https://github.com/ljharb/qs) library.1018 1019> **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.1020 1021### ๐ Automatic serialization to URLSearchParams1022 1023Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".1024 1025```js1026const data = {1027 x: 1,1028 arr: [1, 2, 3],1029 arr2: [1, [2], 3],1030 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],1031};1032 1033await axios.postForm('https://postman-echo.com/post', data,1034 {headers: {'content-type': 'application/x-www-form-urlencoded'}}1035);1036```1037 1038The server will handle it as:1039 1040```js1041 {1042 x: '1',1043 'arr[]': [ '1', '2', '3' ],1044 'arr2[0]': '1',1045 'arr2[1][0]': '2',1046 'arr2[2]': '3',1047 'arr3[]': [ '1', '2', '3' ],1048 'users[0][name]': 'Peter',1049 'users[0][surname]': 'griffin',1050 'users[1][name]': 'Thomas',1051 'users[1][surname]': 'Anderson'1052 }1053````1054 1055If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically1056 1057```js1058 var app = express();1059 1060 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies1061 1062 app.post('/', function (req, res, next) {1063 // echo body as JSON1064 res.send(JSON.stringify(req.body));1065 });1066 1067 server = app.listen(3000);1068```1069 1070## Using `multipart/form-data` format1071 1072### FormData1073 1074To send the data as a `multipart/formdata` you need to pass a formData instance as a payload.1075Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.1076 1077```js1078const formData = new FormData();1079formData.append('foo', 'bar');1080 1081axios.post('https://httpbin.org/post', formData);1082```1083 1084In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:1085 1086```js1087const FormData = require('form-data');1088 1089const form = new FormData();1090form.append('my_field', 'my value');1091form.append('my_buffer', new Buffer(10));1092form.append('my_file', fs.createReadStream('/foo/bar.jpg'));1093 1094axios.post('https://example.com', form)1095```1096 1097### ๐ Automatic serialization to FormData1098 1099Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`1100header is set to `multipart/form-data`.1101 1102The following request will submit the data in a FormData format (Browser & Node.js):1103 1104```js1105import axios from 'axios';1106 1107axios.post('https://httpbin.org/post', {x: 1}, {1108 headers: {1109 'Content-Type': 'multipart/form-data'1110 }1111}).then(({data}) => console.log(data));1112```1113 1114In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.1115 1116You can overload the FormData class by setting the `env.FormData` config variable,1117but you probably won't need it in most cases:1118 1119```js1120const axios = require('axios');1121var FormData = require('form-data');1122 1123axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {1124 headers: {1125 'Content-Type': 'multipart/form-data'1126 }1127}).then(({data}) => console.log(data));1128```1129 1130Axios FormData serializer supports some special endings to perform the following operations:1131 1132- `{}` - serialize the value with JSON.stringify1133- `[]` - unwrap the array-like object as separate fields with the same key1134 1135> **Note**: unwrap/expand operation will be used by default on arrays and FileList objects1136 1137FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:1138 1139- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object1140to a `FormData` object by following custom rules.1141 1142- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;1143 1144- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.1145The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.1146 1147- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects1148 1149 - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)1150 - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)1151 - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)1152 1153Let's say we have an object like this one:1154 1155```js1156const obj = {1157 x: 1,1158 arr: [1, 2, 3],1159 arr2: [1, [2], 3],1160 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],1161 'obj2{}': [{x:1}]1162};1163```1164 1165The following steps will be executed by the Axios serializer internally:1166 1167```js1168const formData = new FormData();1169formData.append('x', '1');1170formData.append('arr[]', '1');1171formData.append('arr[]', '2');1172formData.append('arr[]', '3');1173formData.append('arr2[0]', '1');1174formData.append('arr2[1][0]', '2');1175formData.append('arr2[2]', '3');1176formData.append('users[0][name]', 'Peter');1177formData.append('users[0][surname]', 'Griffin');1178formData.append('users[1][name]', 'Thomas');1179formData.append('users[1][surname]', 'Anderson');1180formData.append('obj2{}', '[{"x":1}]');1181```1182 1183Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`1184which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.1185 1186## Files Posting1187 1188You can easily submit a single file:1189 1190```js1191await axios.postForm('https://httpbin.org/post', {1192 'myVar' : 'foo',1193 'file': document.querySelector('#fileInput').files[0]1194});1195```1196 1197or multiple files as `multipart/form-data`:1198 1199```js1200await axios.postForm('https://httpbin.org/post', {