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