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