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