CoolFace
Apppublic

opusdev/vector-similarity-api

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes
README.md1922 linesDownload Raw Back to axios
1<h3 align="center"> πŸ₯‡ Gold sponsors <br> </h3> <table align="center" width="100%"><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="133px" height="43px" src="https://axios-http.com/assets/sponsors/principal.svg" alt="Principal Financial Group"/> </a> <p align="center" title="We’re bound by one common purpose: to give you the financial tools, resources and information you need to live your best life.">We’re bound by one common purpose: to give you the financial tools, resources and information you ne...</p> <p align="center"> <a href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>www.principal.com</b></a> </p>2</td><td align="center" width="33.333333333333336%"> <a href="https://twicsy.com/buy-instagram-followers?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="85px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/dfa9670ad5e66eea17315332453c7f4e3a3b5905.png" alt="Buy Instagram Followers Twicsy"/> </a> <p align="center" title="Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site to buy followers from the likes of US Magazine.">Buy real Instagram followers from Twicsy starting at only $2.97. Twicsy has been voted the best site...</p> <p align="center"> <a href="https://twicsy.com/buy-instagram-followers?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>twicsy.com</b></a> </p>3</td><td align="center" width="33.333333333333336%"> <a href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <picture> <source width="200px" height="52px" media="(prefers-color-scheme: dark)" srcset="https://axios-http.com/assets/sponsors/descope_white.png"> <img width="200px" height="52px" src="https://axios-http.com/assets/sponsors/descope.png" alt="Descope"/> </picture> </a> <p align="center" title="Hi, we&#x27;re Descope! We are building something in the authentication space for app developers and can’t wait to place it in your hands.">Hi, we&#x27;re Descope! We are building something in the authentication space for app developers and...</p> <p align="center"> <a href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" target="_blank"><b>Website</b></a> | <a href="https://docs.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" target="_blank"><b>Docs</b></a> | <a href="https://www.descope.com/community?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship" target="_blank"><b>Community</b></a> </p>4</td></tr><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://route4me.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <picture> <source width="200px" height="51px" media="(prefers-color-scheme: dark)" srcset="https://axios-http.com/assets/sponsors/route4me_white.png"> <img width="200px" height="51px" src="https://axios-http.com/assets/sponsors/route4me.png" alt="Route4Me"/> </picture> </a> <p align="center" title="Best Route Planning And Route Optimization Software">Best Route Planning And Route Optimization Software</p> <p align="center"> <a href="https://route4me.com/platform/route-optimization-software?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>Explore</b></a> | <a href="https://route4me.com/platform/marketplace/pricing?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>Free Trial</b></a> | <a href="https://route4me.com/contact?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>Contact</b></a> </p>5</td><td align="center" width="33.333333333333336%"> <a href="https://buzzoid.com/buy-instagram-followers/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="62px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/e1625cb54e10ee40180c99d1495a462e9d6664a4.png" alt="Buzzoid - Buy Instagram Followers"/> </a> <p align="center" title="At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rated world&#x27;s #1 IG service since 2012.">At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rate...</p> <p align="center"> <a href="https://buzzoid.com/buy-instagram-followers/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>buzzoid.com</b></a> </p>6</td><td align="center" width="33.333333333333336%"> <a href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="70px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/e699ec99f7df3a203ddbc49d3c7712a907e628ea.png" alt="Poprey - Buy Instagram Likes"/> </a> <p align="center" title="Buy Instagram Likes">Buy Instagram Likes</p> <p align="center"> <a href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>poprey.com</b></a> </p>7</td></tr><tr width="33.333333333333336%"><td align="center" width="33.333333333333336%"> <a href="https://requestly.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship" style="padding: 10px; display: inline-block" target="_blank"> <img width="71px" height="70px" src="https://axios-http.com/assets/sponsors/opencollective/16450b4dc0deb9dab5a511bf2bc8b8b4ac33412f.png" alt="Requestly"/> </a> <p align="center" title="A lightweight open-source API Development, Testing &amp; Mocking platform">A lightweight open-source API Development, Testing &amp; Mocking platform</p> <p align="center"> <a href="https://requestly.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship" target="_blank"><b>requestly.com</b></a> </p>8</td><td align="center" width="33.333333333333336%"> <a href="https://opencollective.com/axios/contribute" target="_blank" >πŸ’œ Become a sponsor</a>9</td><td align="center" width="33.333333333333336%"> <a href="https://opencollective.com/axios/contribute" target="_blank" >πŸ’œ Become a sponsor</a>10</td></tr></table>11 12<!--<div>marker</div>-->13 14<br><br>15 16<div align="center">17   <a href="https://axios-http.com"><img src="https://axios-http.com/assets/logo.svg" alt="Axios" /></a><br>18</div>19 20<p align="center">Promise based HTTP client for the browser and node.js</p>21 22<p align="center">23    <a href="https://axios-http.com/"><b>Website</b></a> β€’24    <a href="https://axios-http.com/docs/intro"><b>Documentation</b></a>25</p>26 27<div align="center">28 29[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)30[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)31[![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=CI&logo=github&style=flat-square)](https://github.com/axios/axios/actions/workflows/ci.yml)32[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/axios/axios)33[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)34[![install size](https://img.shields.io/badge/dynamic/json?url=https://packagephobia.com/v2/api.json?p=axios&query=$.install.pretty&label=install%20size&style=flat-square)](https://packagephobia.now.sh/result?p=axios)35[![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest)36[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios)37[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)38[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)39[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios)40[![Contributors](https://img.shields.io/github/contributors/axios/axios.svg?style=flat-square)](CONTRIBUTORS.md)41 42</div>43 44## Table of Contents45 46- [Features](#features)47- [Browser Support](#browser-support)48- [Installing](#installing)49  - [Package manager](#package-manager)50  - [CDN](#cdn)51- [Example](#example)52- [Axios API](#axios-api)53- [Request method aliases](#request-method-aliases)54- [Concurrency πŸ‘Ž](#concurrency-deprecated)55- [Creating an instance](#creating-an-instance)56- [Instance methods](#instance-methods)57- [Request Config](#request-config)58- [Response Schema](#response-schema)59- [Config Defaults](#config-defaults)60  - [Global axios defaults](#global-axios-defaults)61  - [Custom instance defaults](#custom-instance-defaults)62  - [Config order of precedence](#config-order-of-precedence)63- [Interceptors](#interceptors)64  - [Multiple Interceptors](#multiple-interceptors)65- [Handling Errors](#handling-errors)66- [Handling Timeouts](#handling-timeouts)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](#-rate-limiting)81- [πŸ†• AxiosHeaders](#-axiosheaders)82- [πŸ”₯ Fetch adapter](#-fetch-adapter)83  - [πŸ”₯ Custom fetch](#-custom-fetch)84    - [πŸ”₯ Using with Tauri](#-using-with-tauri)85    - [πŸ”₯ Using with SvelteKit](#-using-with-sveltekit-)86- [πŸ”₯ HTTP2](#-http2)87- [Semver](#semver)88- [Promises](#promises)89- [TypeScript](#typescript)90- [Resources](#resources)91- [Credits](#credits)92- [License](#license)93 94## Features95 96- **Browser Requests:** Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) directly from the browser.97- **Node.js Requests:** Make [http](https://nodejs.org/api/http.html) requests from Node.js environments.98- **Promise-based:** Fully supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API for easier asynchronous code.99- **Interceptors:** Intercept requests and responses to add custom logic or transform data.100- **Data Transformation:** Transform request and response data automatically.101- **Request Cancellation:** Cancel requests using built-in mechanisms.102- **Automatic JSON Handling:** Automatically serializes and parses [JSON](https://www.json.org/json-en.html) data.103- **Form Serialization:** πŸ†• Automatically serializes data objects to `multipart/form-data` or `x-www-form-urlencoded` formats.104- **XSRF Protection:** Client-side support to protect against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery).105 106## Browser Support107 108|                                                     Chrome                                                     |                                                      Firefox                                                      |                                                     Safari                                                     |                                                    Opera                                                    |                                                   Edge                                                   |109| :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------: |110| ![Chrome browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) |111|                                                    Latest βœ”                                                    |                                                     Latest βœ”                                                      |                                                    Latest βœ”                                                    |                                                  Latest βœ”                                                   |                                                 Latest βœ”                                                 |112 113[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)114 115## Installing116 117### Package manager118 119Using npm:120 121```bash122$ npm install axios123```124 125Using bower:126 127```bash128$ bower install axios129```130 131Using yarn:132 133```bash134$ yarn add axios135```136 137Using pnpm:138 139```bash140$ pnpm add axios141```142 143Using bun:144 145```bash146$ bun add axios147```148 149Once the package is installed, you can import the library using `import` or `require` approach:150 151```js152import axios, { isCancel, AxiosError } from "axios";153```154 155You can also use the default export, since the named export is just a re-export from the Axios factory:156 157```js158import axios from "axios";159 160console.log(axios.isCancel("something"));161```162 163If you use `require` for importing, **only the default export is available**:164 165```js166const axios = require("axios");167 168console.log(axios.isCancel("something"));169```170 171For some bundlers and some ES6 linters you may need to do the following:172 173```js174import { default as axios } from "axios";175```176 177For cases where something went wrong when trying to import a module into a custom or legacy environment,178you can try importing the module package directly:179 180```js181const axios = require("axios/dist/browser/axios.cjs"); // browser commonJS bundle (ES2017)182// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)183```184 185### CDN186 187Using jsDelivr CDN (ES5 UMD browser module):188 189```html190<script src="https://cdn.jsdelivr.net/npm/axios@1.13.2/dist/axios.min.js"></script>191```192 193Using unpkg CDN:194 195```html196<script src="https://unpkg.com/axios@1.13.2/dist/axios.min.js"></script>197```198 199## Example200 201```js202import axios from "axios";203//const axios = require('axios'); // legacy way204 205try {206  const response = await axios.get("/user?ID=12345");207  console.log(response);208} catch (error) {209  console.error(error);210}211 212// Optionally the request above could also be done as213axios214  .get("/user", {215    params: {216      ID: 12345,217    },218  })219  .then(function (response) {220    console.log(response);221  })222  .catch(function (error) {223    console.log(error);224  })225  .finally(function () {226    // always executed227  });228 229// Want to use async/await? Add the `async` keyword to your outer function/method.230async function getUser() {231  try {232    const response = await axios.get("/user?ID=12345");233    console.log(response);234  } catch (error) {235    console.error(error);236  }237}238```239 240> **Note**: `async/await` is part of ECMAScript 2017 and is not supported in Internet241> Explorer and older browsers, so use with caution.242 243Performing a `POST` request244 245```js246const response = await axios.post("/user", {247  firstName: "Fred",248  lastName: "Flintstone",249});250console.log(response);251```252 253Performing multiple concurrent requests254 255```js256function getUserAccount() {257  return axios.get("/user/12345");258}259 260function getUserPermissions() {261  return axios.get("/user/12345/permissions");262}263 264Promise.all([getUserAccount(), getUserPermissions()]).then(function (results) {265  const acct = results[0];266  const perm = results[1];267});268```269 270## axios API271 272Requests can be made by passing the relevant config to `axios`.273 274##### axios(config)275 276```js277// Send a POST request278axios({279  method: "post",280  url: "/user/12345",281  data: {282    firstName: "Fred",283    lastName: "Flintstone",284  },285});286```287 288```js289// GET request for remote image in node.js290const response = await axios({291  method: "get",292  url: "https://bit.ly/2mTM3nY",293  responseType: "stream",294});295response.data.pipe(fs.createWriteStream("ada_lovelace.jpg"));296```297 298##### axios(url[, config])299 300```js301// Send a GET request (default method)302axios("/user/12345");303```304 305### Request method aliases306 307For convenience, aliases have been provided for all common request methods.308 309##### axios.request(config)310 311##### axios.get(url[, config])312 313##### axios.delete(url[, config])314 315##### axios.head(url[, config])316 317##### axios.options(url[, config])318 319##### axios.post(url[, data[, config]])320 321##### axios.put(url[, data[, config]])322 323##### axios.patch(url[, data[, config]])324 325###### NOTE326 327When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.328 329### Concurrency (Deprecated)330 331Please use `Promise.all` to replace the below functions.332 333Helper functions for dealing with concurrent requests.334 335axios.all(iterable)336axios.spread(callback)337 338### Creating an instance339 340You can create a new instance of axios with a custom config.341 342##### axios.create([config])343 344```js345const instance = axios.create({346  baseURL: "https://some-domain.com/api/",347  timeout: 1000,348  headers: { "X-Custom-Header": "foobar" },349});350```351 352### Instance methods353 354The available instance methods are listed below. The specified config will be merged with the instance config.355 356##### axios#request(config)357 358##### axios#get(url[, config])359 360##### axios#delete(url[, config])361 362##### axios#head(url[, config])363 364##### axios#options(url[, config])365 366##### axios#post(url[, data[, config]])367 368##### axios#put(url[, data[, config]])369 370##### axios#patch(url[, data[, config]])371 372##### axios#getUri([config])373 374## Request Config375 376These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.377 378```js379{380  // `url` is the server URL that will be used for the request381  url: '/user',382 383  // `method` is the request method to be used when making the request384  method: 'get', // default385 386  // `baseURL` will be prepended to `url` unless `url` is absolute and the option `allowAbsoluteUrls` is set to true.387  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs388  // to the methods of that instance.389  baseURL: 'https://some-domain.com/api/',390 391  // `allowAbsoluteUrls` determines whether or not absolute URLs will override a configured `baseUrl`.392  // When set to true (default), absolute values for `url` will override `baseUrl`.393  // When set to false, absolute values for `url` will always be prepended by `baseUrl`.394  allowAbsoluteUrls: true,395 396  // `transformRequest` allows changes to the request data before it is sent to the server397  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'398  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,399  // FormData or Stream400  // You may modify the headers object.401  transformRequest: [function (data, headers) {402    // Do whatever you want to transform the data403 404    return data;405  }],406 407  // `transformResponse` allows changes to the response data to be made before408  // it is passed to then/catch409  transformResponse: [function (data) {410    // Do whatever you want to transform the data411 412    return data;413  }],414 415  // `headers` are custom headers to be sent416  headers: {'X-Requested-With': 'XMLHttpRequest'},417 418  // `params` are the URL parameters to be sent with the request419  // Must be a plain object or a URLSearchParams object420  params: {421    ID: 12345422  },423 424  // `paramsSerializer` is an optional config that allows you to customize serializing `params`.425  paramsSerializer: {426 427    // Custom encoder function which sends key/value pairs in an iterative fashion.428    encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },429 430    // Custom serializer function for the entire parameter. Allows the user to mimic pre 1.x behaviour.431    serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),432 433    // Configuration for formatting array indexes in the params.434    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).435  },436 437  // `data` is the data to be sent as the request body438  // Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'439  // When no `transformRequest` is set, it must be of one of the following types:440  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams441  // - Browser only: FormData, File, Blob442  // - Node only: Stream, Buffer, FormData (form-data package)443  data: {444    firstName: 'Fred'445  },446 447  // syntax alternative to send data into the body448  // method post449  // only the value is sent, not the key450  data: 'Country=Brasil&City=Belo Horizonte',451 452  // `timeout` specifies the number of milliseconds before the request times out.453  // If the request takes longer than `timeout`, the request will be aborted.454  timeout: 1000, // default is `0` (no timeout)455 456  // `withCredentials` indicates whether or not cross-site Access-Control requests457  // should be made using credentials458  withCredentials: false, // default459 460  // `adapter` allows custom handling of requests which makes testing easier.461  // Return a promise and supply a valid response (see lib/adapters/README.md)462  adapter: function (config) {463    /* ... */464  },465  // Also, you can set the name of the built-in adapter, or provide an array with their names466  // to choose the first available in the environment467  adapter: 'xhr', // 'fetch' | 'http' | ['xhr', 'http', 'fetch']468 469  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.470  // This will set an `Authorization` header, overwriting any existing471  // `Authorization` custom headers you have set using `headers`.472  // Please note that only HTTP Basic auth is configurable through this parameter.473  // For Bearer tokens and such, use `Authorization` custom headers instead.474  auth: {475    username: 'janedoe',476    password: 's00pers3cret'477  },478 479  // `responseType` indicates the type of data that the server will respond with480  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'481  //   browser only: 'blob'482  responseType: 'json', // default483 484  // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)485  // Note: Ignored for `responseType` of 'stream' or client-side requests486  // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',487  // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',488  // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'489  responseEncoding: 'utf8', // default490 491  // `xsrfCookieName` is the name of the cookie to use as a value for the xsrf token492  xsrfCookieName: 'XSRF-TOKEN', // default493 494  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value495  xsrfHeaderName: 'X-XSRF-TOKEN', // default496 497  // `undefined` (default) - set XSRF header only for the same origin requests498  withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),499 500  // `onUploadProgress` allows handling of progress events for uploads501  // browser & node.js502  onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {503    // Do whatever you want with the Axios progress event504  },505 506  // `onDownloadProgress` allows handling of progress events for downloads507  // browser & node.js508  onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {509    // Do whatever you want with the Axios progress event510  },511 512  // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js513  maxContentLength: 2000,514 515  // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed516  maxBodyLength: 2000,517 518  // `validateStatus` defines whether to resolve or reject the promise for a given519  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`520  // or `undefined`), the promise will be resolved; otherwise, the promise will be521  // rejected.522  validateStatus: function (status) {523    return status >= 200 && status < 300; // default524  },525 526  // `maxRedirects` defines the maximum number of redirects to follow in node.js.527  // If set to 0, no redirects will be followed.528  maxRedirects: 21, // default529 530  // `beforeRedirect` defines a function that will be called before redirect.531  // Use this to adjust the request options upon redirecting,532  // to inspect the latest response headers,533  // or to cancel the request by throwing an error534  // If maxRedirects is set to 0, `beforeRedirect` is not used.535  beforeRedirect: (options, { headers }) => {536    if (options.hostname === "example.com") {537      options.auth = "user:password";538    }539  },540 541  // `socketPath` defines a UNIX Socket to be used in node.js.542  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.543  // Only either `socketPath` or `proxy` can be specified.544  // If both are specified, `socketPath` is used.545  socketPath: null, // default546 547  // `transport` determines the transport method that will be used to make the request.548  // If defined, it will be used. Otherwise, if `maxRedirects` is 0,549  // the default `http` or `https` library will be used, depending on the protocol specified in `protocol`.550  // Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol,551  // 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 before Node.js v19.0.0. After Node.js557  // v19.0.0, you no longer need to customize the agent to enable `keepAlive` because558  // `http.globalAgent` has `keepAlive` enabled by default.559  httpAgent: new http.Agent({ keepAlive: true }),560  httpsAgent: new https.Agent({ keepAlive: true }),561 562  // `proxy` defines the hostname, port, and protocol of the proxy server.563  // You can also define your proxy using the conventional `http_proxy` and564  // `https_proxy` environment variables. If you are using environment variables565  // for your proxy configuration, you can also define a `no_proxy` environment566  // variable as a comma-separated list of domains that should not be proxied.567  // Use `false` to disable proxies, ignoring environment variables.568  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and569  // supplies credentials.570  // This will set a `Proxy-Authorization` header, overwriting any existing571  // `Proxy-Authorization` custom headers you have set using `headers`.572  // If the proxy server uses HTTPS, then you must set the protocol to `https`.573  proxy: {574    protocol: 'https',575    host: '127.0.0.1',576    // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined577    port: 9000,578    auth: {579      username: 'mikeymike',580      password: 'rapunz3l'581    }582  },583 584  // `cancelToken` specifies a cancel token that can be used to cancel the request585  // (see Cancellation section below for details)586  cancelToken: new CancelToken(function (cancel) {587  }),588 589  // an alternative way to cancel Axios requests using AbortController590  signal: new AbortController().signal,591 592  // `decompress` indicates whether or not the response body should be decompressed593  // automatically. If set to `true` will also remove the 'content-encoding' header594  // from the responses objects of all decompressed responses595  // - Node only (XHR cannot turn off decompression)596  decompress: true, // default597 598  // `insecureHTTPParser` boolean.599  // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.600  // This may allow interoperability with non-conformant HTTP implementations.601  // Using the insecure parser should be avoided.602  // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback603  // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none604  insecureHTTPParser: undefined, // default605 606  // transitional options for backward compatibility that may be removed in the newer versions607  transitional: {608    // silent JSON parsing mode609    // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)610    // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')611    silentJSONParsing: true, // default value for the current Axios version612 613    // try to parse the response string as JSON even if `responseType` is not 'json'614    forcedJSONParsing: true,615 616    // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts617    clarifyTimeoutError: false,618 619    // use the legacy interceptor request/response ordering620    legacyInterceptorReqResOrdering: true, // default621  },622 623  env: {624    // The FormData class to be used to automatically serialize the payload into a FormData object625    FormData: window?.FormData || global?.FormData626  },627 628  formSerializer: {629      visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values630      dots: boolean; // use dots instead of brackets format631      metaTokens: boolean; // keep special endings like {} in parameter key632      indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes633  },634 635  // http adapter only (node.js)636  maxRate: [637    100 * 1024, // 100KB/s upload limit,638    100 * 1024  // 100KB/s download limit639  ]640}641```642 643## Response Schema644 645The response to a request contains the following information.646 647```js648{649  // `data` is the response that was provided by the server650  data: {},651 652  // `status` is the HTTP status code from the server response653  status: 200,654 655  // `statusText` is the HTTP status message from the server response656  statusText: 'OK',657 658  // `headers` the HTTP headers that the server responded with659  // All header names are lowercase and can be accessed using the bracket notation.660  // Example: `response.headers['content-type']`661  headers: {},662 663  // `config` is the config that was provided to `axios` for the request664  config: {},665 666  // `request` is the request that generated this response667  // It is the last ClientRequest instance in node.js (in redirects)668  // and an XMLHttpRequest instance in the browser669  request: {}670}671```672 673When using `then`, you will receive the response as follows:674 675```js676const response = await axios.get("/user/12345");677console.log(response.data);678console.log(response.status);679console.log(response.statusText);680console.log(response.headers);681console.log(response.config);682```683 684When 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.685 686## Config Defaults687 688You can specify config defaults that will be applied to every request.689 690### Global axios defaults691 692```js693axios.defaults.baseURL = "https://api.example.com";694 695// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.696// See below for an example using Custom instance defaults instead.697axios.defaults.headers.common["Authorization"] = AUTH_TOKEN;698 699axios.defaults.headers.post["Content-Type"] =700  "application/x-www-form-urlencoded";701```702 703### Custom instance defaults704 705```js706// Set config defaults when creating the instance707const instance = axios.create({708  baseURL: "https://api.example.com",709});710 711// Alter defaults after instance has been created712instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;713```714 715### Config order of precedence716 717Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults/index.js](https://github.com/axios/axios/blob/main/lib/defaults/index.js#L49), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.718 719```js720// Create an instance using the config defaults provided by the library721// At this point the timeout config value is `0` as is the default for the library722const instance = axios.create();723 724// Override timeout default for the library725// Now all requests using this instance will wait 2.5 seconds before timing out726instance.defaults.timeout = 2500;727 728// Override timeout for this request as it's known to take a long time729instance.get("/longRequest", {730  timeout: 5000,731});732```733 734## Interceptors735 736You can intercept requests or responses before methods like `.get()` or `.post()`737resolve their promises (before code inside `then` or `catch`, or after `await`)738 739```js740const instance = axios.create();741 742// Add a request interceptor743instance.interceptors.request.use(744  function (config) {745    // Do something before the request is sent746    return config;747  },748  function (error) {749    // Do something with the request error750    return Promise.reject(error);751  },752);753 754// Add a response interceptor755instance.interceptors.response.use(756  function (response) {757    // Any status code that lies within the range of 2xx causes this function to trigger758    // Do something with response data759    return response;760  },761  function (error) {762    // Any status codes that fall outside the range of 2xx cause this function to trigger763    // Do something with response error764    return Promise.reject(error);765  },766);767```768 769If you need to remove an interceptor later you can.770 771```js772const instance = axios.create();773const myInterceptor = instance.interceptors.request.use(function () {774  /*...*/775});776axios.interceptors.request.eject(myInterceptor);777```778 779You can also clear all interceptors for requests or responses.780 781```js782const instance = axios.create();783instance.interceptors.request.use(function () {784  /*...*/785});786instance.interceptors.request.clear(); // Removes interceptors from requests787instance.interceptors.response.use(function () {788  /*...*/789});790instance.interceptors.response.clear(); // Removes interceptors from responses791```792 793You can add interceptors to a custom instance of axios.794 795```js796const instance = axios.create();797instance.interceptors.request.use(function () {798  /*...*/799});800```801 802When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay803in the execution of your axios request when the main thread is blocked (a promise is created under the hood for804the interceptor and your request gets put at the bottom of the call stack). If your request interceptors are synchronous you can add a flag805to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.806 807```js808axios.interceptors.request.use(809  function (config) {810    config.headers.test = "I am only a header!";811    return config;812  },813  null,814  { synchronous: true },815);816```817 818If you want to execute a particular interceptor based on a runtime check,819you can add a `runWhen` function to the options object. The request interceptor will not be executed **if and only if** the return820of `runWhen` is `false`. The function will be called with the config821object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an822asynchronous request interceptor that only needs to run at certain times.823 824```js825function onGetCall(config) {826  return config.method === "get";827}828axios.interceptors.request.use(829  function (config) {830    config.headers.test = "special get headers";831    return config;832  },833  null,834  { runWhen: onGetCall },835);836```837 838> **Note:** The options parameter(having `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment.839 840### Interceptor Execution Order841 842**Important:** Interceptors have different execution orders depending on their type!843 844Request interceptors are executed in **reverse order** (LIFO - Last In, First Out). This means the _last_ interceptor added is executed **first**.845 846Response interceptors are executed in the **order they were added** (FIFO - First In, First Out). This means the _first_ interceptor added is executed **first**.847 848Example:849 850```js851const instance = axios.create();852 853const interceptor = (id) => (base) => {854  console.log(id);855  return base;856};857 858instance.interceptors.request.use(interceptor("Request Interceptor 1"));859instance.interceptors.request.use(interceptor("Request Interceptor 2"));860instance.interceptors.request.use(interceptor("Request Interceptor 3"));861instance.interceptors.response.use(interceptor("Response Interceptor 1"));862instance.interceptors.response.use(interceptor("Response Interceptor 2"));863instance.interceptors.response.use(interceptor("Response Interceptor 3"));864 865// Console output:866// Request Interceptor 3867// Request Interceptor 2868// Request Interceptor 1869// [HTTP request is made]870// Response Interceptor 1871// Response Interceptor 2872// Response Interceptor 3873```874 875### Multiple Interceptors876 877Given that you add multiple response interceptors878and when the response was fulfilled879 880- then each interceptor is executed881- then they are executed in the order they were added882- then only the last interceptor's result is returned883- then every interceptor receives the result of its predecessor884- and when the fulfillment-interceptor throws885  - then the following fulfillment-interceptor is not called886  - then the following rejection-interceptor is called887  - once caught, another following fulfill-interceptor is called again (just like in a promise chain).888 889Read [the interceptor tests](./test/specs/interceptors.spec.js) to see all this in code.890 891## Error Types892 893There are many different axios error messages that can appear which can provide basic information about the specifics of the error and where opportunities may lie in debugging.894 895The general structure of axios errors is as follows:896| Property | Definition |897| -------- | ---------- |898| message | A quick summary of the error message and the status it failed with. |899| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. |900| stack | Provides the stack trace of the error. |901| config | An axios config object with specific instance configurations defined by the user from when the request was made |902| code | Represents an axios identified error. The table below lists specific definitions for internal axios error. |903| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings.904 905Below is a list of potential axios identified error:906 907| Code                      | Definition                                                                                                                                                                                                                                                                                                                                                                                     |908| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |909| ERR_BAD_OPTION_VALUE      | Invalid value provided in axios configuration.                                                                                                                                                                                                                                                                                                                                                 |910| ERR_BAD_OPTION            | Invalid option provided in axios configuration.                                                                                                                                                                                                                                                                                                                                                |911| ERR_NOT_SUPPORT           | Feature or method not supported in the current axios environment.                                                                                                                                                                                                                                                                                                                              |912| ERR_DEPRECATED            | Deprecated feature or method used in axios.                                                                                                                                                                                                                                                                                                                                                    |913| ERR_INVALID_URL           | Invalid URL provided for axios request.                                                                                                                                                                                                                                                                                                                                                        |914| ECONNABORTED              | Typically indicates that the request has been timed out (unless `transitional.clarifyTimeoutError` is set) or aborted by the browser or its plugin.                                                                                                                                                                                                                                            |915| ERR_CANCELED              | Feature or method is canceled explicitly by the user using an AbortSignal (or a CancelToken).                                                                                                                                                                                                                                                                                                  |916| ETIMEDOUT                 | Request timed out due to exceeding the default axios timelimit. `transitional.clarifyTimeoutError` must be set to `true`, otherwise a generic `ECONNABORTED` error will be thrown instead.                                                                                                                                                                                                     |917| ERR_NETWORK               | Network-related issue. In the browser, this error can also be caused by a [CORS](https://developer.mozilla.org/ru/docs/Web/HTTP/Guides/CORS) or [Mixed Content](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content) policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console. |918| ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration.                                                                                                                                                                                                                                                                                                  |919| ERR_BAD_RESPONSE          | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with `5xx` status code.                                                                                                                                                                                                                                                                        |920| ERR_BAD_REQUEST           | The request has an unexpected format or is missing required parameters. Usually related to a response with `4xx` status code.                                                                                                                                                                                                                                                                  |921 922## Handling Errors923 924The 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.925 926```js927axios.get("/user/12345").catch(function (error) {928  if (error.response) {929    // The request was made and the server responded with a status code930    // that falls out of the range of 2xx931    console.log(error.response.data);932    console.log(error.response.status);933    console.log(error.response.headers);934  } else if (error.request) {935    // The request was made but no response was received936    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of937    // http.ClientRequest in node.js938    console.log(error.request);939  } else {940    // Something happened in setting up the request that triggered an Error941    console.log("Error", error.message);942  }943  console.log(error.config);944});945```946 947Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.948 949```js950axios.get("/user/12345", {951  validateStatus: function (status) {952    return status < 500; // Resolve only if the status code is less than 500953  },954});955```956 957Using `toJSON` you get an object with more information about the HTTP error.958 959```js960axios.get("/user/12345").catch(function (error) {961  console.log(error.toJSON());962});963```964 965## Handling Timeouts966 967```js968async function fetchWithTimeout() {969  try {970    const response = await axios.get("https://example.com/data", {971      timeout: 5000, // 5 seconds972    });973 974    console.log("Response:", response.data);975  } catch (error) {976    if (axios.isAxiosError(error) && error.code === "ECONNABORTED") {977      console.error("❌ Request timed out!");978    } else {979      console.error("❌ Error:", error.message);980    }981  }982}983```984 985## Cancellation986 987### AbortController988 989Starting from `v0.22.0` Axios supports AbortController to cancel requests in a fetch API way:990 991```js992const controller = new AbortController();993 994axios995  .get("/foo/bar", {996    signal: controller.signal,997  })998  .then(function (response) {999    //...1000  });1001// cancel the request1002controller.abort();1003```1004 1005### CancelToken `πŸ‘Ždeprecated`1006 1007You can also cancel a request using a _CancelToken_.1008 1009> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).1010 1011> This API is deprecated since v0.22.0 and shouldn't be used in new projects1012 1013You can create a cancel token using the `CancelToken.source` factory as shown below:1014 1015```js1016const CancelToken = axios.CancelToken;1017const source = CancelToken.source();1018 1019axios1020  .get("/user/12345", {1021    cancelToken: source.token,1022  })1023  .catch(function (thrown) {1024    if (axios.isCancel(thrown)) {1025      console.log("Request canceled", thrown.message);1026    } else {1027      // handle error1028    }1029  });1030 1031axios.post(1032  "/user/12345",1033  {1034    name: "new name",1035  },1036  {1037    cancelToken: source.token,1038  },1039);1040 1041// cancel the request (the message parameter is optional)1042source.cancel("Operation canceled by the user.");1043```1044 1045You can also create a cancel token by passing an executor function to the `CancelToken` constructor:1046 1047```js1048const CancelToken = axios.CancelToken;1049let cancel;1050 1051axios.get("/user/12345", {1052  cancelToken: new CancelToken(function executor(c) {1053    // An executor function receives a cancel function as a parameter1054    cancel = c;1055  }),1056});1057 1058// cancel the request1059cancel();1060```1061 1062> **Note:** you can cancel several requests with the same cancel token/abort controller.1063> 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.1064 1065> During the transition period, you can use both cancellation APIs, even for the same request:1066 1067## Using `application/x-www-form-urlencoded` format1068 1069### URLSearchParams1070 1071By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) format instead, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is [supported](http://www.caniuse.com/#feat=urlsearchparams) in the vast majority of browsers, and [Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) starting with v10 (released in 2018).1072 1073```js1074const params = new URLSearchParams({ foo: "bar" });1075params.append("extraparam", "value");1076axios.post("/foo", params);1077```1078 1079### Query string (Older browsers)1080 1081For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).1082 1083Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:1084 1085```js1086const qs = require("qs");1087axios.post("/foo", qs.stringify({ bar: 123 }));1088```1089 1090Or in another way (ES6),1091 1092```js1093import qs from "qs";1094const data = { bar: 123 };1095const options = {1096  method: "POST",1097  headers: { "content-type": "application/x-www-form-urlencoded" },1098  data: qs.stringify(data),1099  url,1100};1101axios(options);1102```1103 1104### Older Node.js versions1105 1106For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:1107 1108```js1109const querystring = require("querystring");1110axios.post("https://something.com/", querystring.stringify({ foo: "bar" }));1111```1112 1113You can also use the [`qs`](https://github.com/ljharb/qs) library.1114 1115> **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.1116 1117### πŸ†• Automatic serialization to URLSearchParams1118 1119Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".1120 1121```js1122const data = {1123  x: 1,1124  arr: [1, 2, 3],1125  arr2: [1, [2], 3],1126  users: [1127    { name: "Peter", surname: "Griffin" },1128    { name: "Thomas", surname: "Anderson" },1129  ],1130};1131 1132await axios.postForm("https://postman-echo.com/post", data, {1133  headers: { "content-type": "application/x-www-form-urlencoded" },1134});1135```1136 1137The server will handle it as:1138 1139```js1140  {1141    x: '1',1142    'arr[]': [ '1', '2', '3' ],1143    'arr2[0]': '1',1144    'arr2[1][0]': '2',1145    'arr2[2]': '3',1146    'arr3[]': [ '1', '2', '3' ],1147    'users[0][name]': 'Peter',1148    'users[0][surname]': 'griffin',1149    'users[1][name]': 'Thomas',1150    'users[1][surname]': 'Anderson'1151  }1152```1153 1154If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically1155 1156```js1157const app = express();1158 1159app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies1160 1161app.post("/", function (req, res, next) {1162  // echo body as JSON1163  res.send(JSON.stringify(req.body));1164});1165 1166server = app.listen(3000);1167```1168 1169## Using `multipart/form-data` format1170 1171### FormData1172 1173To send the data as a `multipart/form-data` you need to pass a formData instance as a payload.1174Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.1175 1176```js1177const formData = new FormData();1178formData.append("foo", "bar");1179 1180axios.post("https://httpbin.org/post", formData);1181```1182 1183In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:1184 1185```js1186const FormData = require("form-data");1187 1188const form = new FormData();1189form.append("my_field", "my value");1190form.append("my_buffer", Buffer.alloc(10));1191form.append("my_file", fs.createReadStream("/foo/bar.jpg"));1192 1193axios.post("https://example.com", form);1194```1195 1196### πŸ†• Automatic serialization to FormData1197 1198Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`1199header is set to `multipart/form-data`.1200 

Showing the first 1,200 of 1922 lines. Download the file for the rest.