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