UNPKG

43.9 kBMarkdownView Raw
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/workflow/status/axios/axios/ci?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 - [Semver](#semver)
70 - [Promises](#promises)
71 - [TypeScript](#typescript)
72 - [Resources](#resources)
73 - [Credits](#credits)
74 - [License](#license)
75
76## Features
77
78- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
79- Make [http](https://nodejs.org/api/http.html) requests from node.js
80- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
81- Intercept request and response
82- Transform request and response data
83- Cancel requests
84- Automatic transforms for [JSON](https://www.json.org/json-en.html) data
85- 🆕 Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings
86- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)
87
88## Browser Support
89
90![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) |
91--- | --- | --- | --- | --- | --- |
92Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
93
94[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
95
96## Installing
97
98### Package manager
99
100Using npm:
101
102```bash
103$ npm install axios
104```
105
106Using bower:
107
108```bash
109$ bower install axios
110```
111
112Using yarn:
113
114```bash
115$ yarn add axios
116```
117
118Using pnpm:
119
120```bash
121$ pnpm add axios
122```
123
124Once the package is installed, you can import the library using `import` or `require` approach:
125
126```js
127import axios, {isCancel, AxiosError} from 'axios';
128```
129
130You can also use the default export, since the named export is just a re-export from the Axios factory:
131
132```js
133import axios from 'axios';
134
135console.log(axios.isCancel('something'));
136````
137
138If you use `require` for importing, **only default export is available**:
139
140```js
141const axios = require('axios');
142
143console.log(axios.isCancel('something'));
144```
145
146For cases where something went wrong when trying to import a module into a custom or legacy environment,
147you can try importing the module package directly:
148
149```js
150const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
151// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
152```
153
154### CDN
155
156Using jsDelivr CDN (ES5 UMD browser module):
157
158```html
159<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
160```
161
162Using unpkg CDN:
163
164```html
165<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
166```
167
168## Example
169
170> **Note** CommonJS usage
171> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach:
172
173```js
174import axios from 'axios';
175//const axios = require('axios'); // legacy way
176
177// Make a request for a user with a given ID
178axios.get('/user?ID=12345')
179 .then(function (response) {
180 // handle success
181 console.log(response);
182 })
183 .catch(function (error) {
184 // handle error
185 console.log(error);
186 })
187 .finally(function () {
188 // always executed
189 });
190
191// Optionally the request above could also be done as
192axios.get('/user', {
193 params: {
194 ID: 12345
195 }
196 })
197 .then(function (response) {
198 console.log(response);
199 })
200 .catch(function (error) {
201 console.log(error);
202 })
203 .finally(function () {
204 // always executed
205 });
206
207// Want to use async/await? Add the `async` keyword to your outer function/method.
208async function getUser() {
209 try {
210 const response = await axios.get('/user?ID=12345');
211 console.log(response);
212 } catch (error) {
213 console.error(error);
214 }
215}
216```
217
218> **Note** `async/await` is part of ECMAScript 2017 and is not supported in Internet
219> Explorer and older browsers, so use with caution.
220
221Performing a `POST` request
222
223```js
224axios.post('/user', {
225 firstName: 'Fred',
226 lastName: 'Flintstone'
227 })
228 .then(function (response) {
229 console.log(response);
230 })
231 .catch(function (error) {
232 console.log(error);
233 });
234```
235
236Performing multiple concurrent requests
237
238```js
239function getUserAccount() {
240 return axios.get('/user/12345');
241}
242
243function getUserPermissions() {
244 return axios.get('/user/12345/permissions');
245}
246
247Promise.all([getUserAccount(), getUserPermissions()])
248 .then(function (results) {
249 const acct = results[0];
250 const perm = results[1];
251 });
252```
253
254## axios API
255
256Requests can be made by passing the relevant config to `axios`.
257
258##### axios(config)
259
260```js
261// Send a POST request
262axios({
263 method: 'post',
264 url: '/user/12345',
265 data: {
266 firstName: 'Fred',
267 lastName: 'Flintstone'
268 }
269});
270```
271
272```js
273// GET request for remote image in node.js
274axios({
275 method: 'get',
276 url: 'https://bit.ly/2mTM3nY',
277 responseType: 'stream'
278})
279 .then(function (response) {
280 response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
281 });
282```
283
284##### axios(url[, config])
285
286```js
287// Send a GET request (default method)
288axios('/user/12345');
289```
290
291### Request method aliases
292
293For convenience, aliases have been provided for all common request methods.
294
295##### axios.request(config)
296##### axios.get(url[, config])
297##### axios.delete(url[, config])
298##### axios.head(url[, config])
299##### axios.options(url[, config])
300##### axios.post(url[, data[, config]])
301##### axios.put(url[, data[, config]])
302##### axios.patch(url[, data[, config]])
303
304###### NOTE
305When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
306
307### Concurrency (Deprecated)
308Please use `Promise.all` to replace the below functions.
309
310Helper functions for dealing with concurrent requests.
311
312axios.all(iterable)
313axios.spread(callback)
314
315### Creating an instance
316
317You can create a new instance of axios with a custom config.
318
319##### axios.create([config])
320
321```js
322const instance = axios.create({
323 baseURL: 'https://some-domain.com/api/',
324 timeout: 1000,
325 headers: {'X-Custom-Header': 'foobar'}
326});
327```
328
329### Instance methods
330
331The available instance methods are listed below. The specified config will be merged with the instance config.
332
333##### axios#request(config)
334##### axios#get(url[, config])
335##### axios#delete(url[, config])
336##### axios#head(url[, config])
337##### axios#options(url[, config])
338##### axios#post(url[, data[, config]])
339##### axios#put(url[, data[, config]])
340##### axios#patch(url[, data[, config]])
341##### axios#getUri([config])
342
343## Request Config
344
345These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
346
347```js
348{
349 // `url` is the server URL that will be used for the request
350 url: '/user',
351
352 // `method` is the request method to be used when making the request
353 method: 'get', // default
354
355 // `baseURL` will be prepended to `url` unless `url` is absolute.
356 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
357 // to methods of that instance.
358 baseURL: 'https://some-domain.com/api/',
359
360 // `transformRequest` allows changes to the request data before it is sent to the server
361 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
362 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
363 // FormData or Stream
364 // You may modify the headers object.
365 transformRequest: [function (data, headers) {
366 // Do whatever you want to transform the data
367
368 return data;
369 }],
370
371 // `transformResponse` allows changes to the response data to be made before
372 // it is passed to then/catch
373 transformResponse: [function (data) {
374 // Do whatever you want to transform the data
375
376 return data;
377 }],
378
379 // `headers` are custom headers to be sent
380 headers: {'X-Requested-With': 'XMLHttpRequest'},
381
382 // `params` are the URL parameters to be sent with the request
383 // Must be a plain object or a URLSearchParams object
384 params: {
385 ID: 12345
386 },
387
388 // `paramsSerializer` is an optional config in charge of serializing `params`
389 paramsSerializer: {
390 encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashion
391 serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized.
392 indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes)
393 },
394
395 // `data` is the data to be sent as the request body
396 // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
397 // When no `transformRequest` is set, must be of one of the following types:
398 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
399 // - Browser only: FormData, File, Blob
400 // - Node only: Stream, Buffer, FormData (form-data package)
401 data: {
402 firstName: 'Fred'
403 },
404
405 // syntax alternative to send data into the body
406 // method post
407 // only the value is sent, not the key
408 data: 'Country=Brasil&City=Belo Horizonte',
409
410 // `timeout` specifies the number of milliseconds before the request times out.
411 // If the request takes longer than `timeout`, the request will be aborted.
412 timeout: 1000, // default is `0` (no timeout)
413
414 // `withCredentials` indicates whether or not cross-site Access-Control requests
415 // should be made using credentials
416 withCredentials: false, // default
417
418 // `adapter` allows custom handling of requests which makes testing easier.
419 // Return a promise and supply a valid response (see lib/adapters/README.md).
420 adapter: function (config) {
421 /* ... */
422 },
423
424 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
425 // This will set an `Authorization` header, overwriting any existing
426 // `Authorization` custom headers you have set using `headers`.
427 // Please note that only HTTP Basic auth is configurable through this parameter.
428 // For Bearer tokens and such, use `Authorization` custom headers instead.
429 auth: {
430 username: 'janedoe',
431 password: 's00pers3cret'
432 },
433
434 // `responseType` indicates the type of data that the server will respond with
435 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
436 // browser only: 'blob'
437 responseType: 'json', // default
438
439 // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
440 // Note: Ignored for `responseType` of 'stream' or client-side requests
441 responseEncoding: 'utf8', // default
442
443 // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
444 xsrfCookieName: 'XSRF-TOKEN', // default
445
446 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
447 xsrfHeaderName: 'X-XSRF-TOKEN', // default
448
449 // `onUploadProgress` allows handling of progress events for uploads
450 // browser & node.js
451 onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
452 // Do whatever you want with the Axios progress event
453 },
454
455 // `onDownloadProgress` allows handling of progress events for downloads
456 // browser & node.js
457 onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
458 // Do whatever you want with the Axios progress event
459 },
460
461 // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
462 maxContentLength: 2000,
463
464 // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
465 maxBodyLength: 2000,
466
467 // `validateStatus` defines whether to resolve or reject the promise for a given
468 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
469 // or `undefined`), the promise will be resolved; otherwise, the promise will be
470 // rejected.
471 validateStatus: function (status) {
472 return status >= 200 && status < 300; // default
473 },
474
475 // `maxRedirects` defines the maximum number of redirects to follow in node.js.
476 // If set to 0, no redirects will be followed.
477 maxRedirects: 21, // default
478
479 // `beforeRedirect` defines a function that will be called before redirect.
480 // Use this to adjust the request options upon redirecting,
481 // to inspect the latest response headers,
482 // or to cancel the request by throwing an error
483 // If maxRedirects is set to 0, `beforeRedirect` is not used.
484 beforeRedirect: (options, { headers }) => {
485 if (options.hostname === "example.com") {
486 options.auth = "user:password";
487 }
488 },
489
490 // `socketPath` defines a UNIX Socket to be used in node.js.
491 // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
492 // Only either `socketPath` or `proxy` can be specified.
493 // If both are specified, `socketPath` is used.
494 socketPath: null, // default
495
496 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
497 // and https requests, respectively, in node.js. This allows options to be added like
498 // `keepAlive` that are not enabled by default.
499 httpAgent: new http.Agent({ keepAlive: true }),
500 httpsAgent: new https.Agent({ keepAlive: true }),
501
502 // `proxy` defines the hostname, port, and protocol of the proxy server.
503 // You can also define your proxy using the conventional `http_proxy` and
504 // `https_proxy` environment variables. If you are using environment variables
505 // for your proxy configuration, you can also define a `no_proxy` environment
506 // variable as a comma-separated list of domains that should not be proxied.
507 // Use `false` to disable proxies, ignoring environment variables.
508 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
509 // supplies credentials.
510 // This will set an `Proxy-Authorization` header, overwriting any existing
511 // `Proxy-Authorization` custom headers you have set using `headers`.
512 // If the proxy server uses HTTPS, then you must set the protocol to `https`.
513 proxy: {
514 protocol: 'https',
515 host: '127.0.0.1',
516 // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
517 port: 9000,
518 auth: {
519 username: 'mikeymike',
520 password: 'rapunz3l'
521 }
522 },
523
524 // `cancelToken` specifies a cancel token that can be used to cancel the request
525 // (see Cancellation section below for details)
526 cancelToken: new CancelToken(function (cancel) {
527 }),
528
529 // an alternative way to cancel Axios requests using AbortController
530 signal: new AbortController().signal,
531
532 // `decompress` indicates whether or not the response body should be decompressed
533 // automatically. If set to `true` will also remove the 'content-encoding' header
534 // from the responses objects of all decompressed responses
535 // - Node only (XHR cannot turn off decompression)
536 decompress: true // default
537
538 // `insecureHTTPParser` boolean.
539 // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
540 // This may allow interoperability with non-conformant HTTP implementations.
541 // Using the insecure parser should be avoided.
542 // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
543 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
544 insecureHTTPParser: undefined // default
545
546 // transitional options for backward compatibility that may be removed in the newer versions
547 transitional: {
548 // silent JSON parsing mode
549 // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
550 // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
551 silentJSONParsing: true, // default value for the current Axios version
552
553 // try to parse the response string as JSON even if `responseType` is not 'json'
554 forcedJSONParsing: true,
555
556 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
557 clarifyTimeoutError: false,
558 },
559
560 env: {
561 // The FormData class to be used to automatically serialize the payload into a FormData object
562 FormData: window?.FormData || global?.FormData
563 },
564
565 formSerializer: {
566 visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
567 dots: boolean; // use dots instead of brackets format
568 metaTokens: boolean; // keep special endings like {} in parameter key
569 indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
570 },
571
572 // http adapter only (node.js)
573 maxRate: [
574 100 * 1024, // 100KB/s upload limit,
575 100 * 1024 // 100KB/s download limit
576 ]
577}
578```
579
580## Response Schema
581
582The response for a request contains the following information.
583
584```js
585{
586 // `data` is the response that was provided by the server
587 data: {},
588
589 // `status` is the HTTP status code from the server response
590 status: 200,
591
592 // `statusText` is the HTTP status message from the server response
593 statusText: 'OK',
594
595 // `headers` the HTTP headers that the server responded with
596 // All header names are lowercase and can be accessed using the bracket notation.
597 // Example: `response.headers['content-type']`
598 headers: {},
599
600 // `config` is the config that was provided to `axios` for the request
601 config: {},
602
603 // `request` is the request that generated this response
604 // It is the last ClientRequest instance in node.js (in redirects)
605 // and an XMLHttpRequest instance in the browser
606 request: {}
607}
608```
609
610When using `then`, you will receive the response as follows:
611
612```js
613axios.get('/user/12345')
614 .then(function (response) {
615 console.log(response.data);
616 console.log(response.status);
617 console.log(response.statusText);
618 console.log(response.headers);
619 console.log(response.config);
620 });
621```
622
623When 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.
624
625## Config Defaults
626
627You can specify config defaults that will be applied to every request.
628
629### Global axios defaults
630
631```js
632axios.defaults.baseURL = 'https://api.example.com';
633
634// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
635// See below for an example using Custom instance defaults instead.
636axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
637
638axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
639```
640
641### Custom instance defaults
642
643```js
644// Set config defaults when creating the instance
645const instance = axios.create({
646 baseURL: 'https://api.example.com'
647});
648
649// Alter defaults after instance has been created
650instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
651```
652
653### Config order of precedence
654
655Config 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.
656
657```js
658// Create an instance using the config defaults provided by the library
659// At this point the timeout config value is `0` as is the default for the library
660const instance = axios.create();
661
662// Override timeout default for the library
663// Now all requests using this instance will wait 2.5 seconds before timing out
664instance.defaults.timeout = 2500;
665
666// Override timeout for this request as it's known to take a long time
667instance.get('/longRequest', {
668 timeout: 5000
669});
670```
671
672## Interceptors
673
674You can intercept requests or responses before they are handled by `then` or `catch`.
675
676```js
677// Add a request interceptor
678axios.interceptors.request.use(function (config) {
679 // Do something before request is sent
680 return config;
681 }, function (error) {
682 // Do something with request error
683 return Promise.reject(error);
684 });
685
686// Add a response interceptor
687axios.interceptors.response.use(function (response) {
688 // Any status code that lie within the range of 2xx cause this function to trigger
689 // Do something with response data
690 return response;
691 }, function (error) {
692 // Any status codes that falls outside the range of 2xx cause this function to trigger
693 // Do something with response error
694 return Promise.reject(error);
695 });
696```
697
698If you need to remove an interceptor later you can.
699
700```js
701const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
702axios.interceptors.request.eject(myInterceptor);
703```
704
705You can also clear all interceptors for requests or responses.
706```js
707const instance = axios.create();
708instance.interceptors.request.use(function () {/*...*/});
709instance.interceptors.request.clear(); // Removes interceptors from requests
710instance.interceptors.response.use(function () {/*...*/});
711instance.interceptors.response.clear(); // Removes interceptors from responses
712```
713
714You can add interceptors to a custom instance of axios.
715
716```js
717const instance = axios.create();
718instance.interceptors.request.use(function () {/*...*/});
719```
720
721When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
722in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
723the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
724to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
725
726```js
727axios.interceptors.request.use(function (config) {
728 config.headers.test = 'I am only a header!';
729 return config;
730}, null, { synchronous: true });
731```
732
733If you want to execute a particular interceptor based on a runtime check,
734you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return
735of `runWhen` is `false`. The function will be called with the config
736object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
737asynchronous request interceptor that only needs to run at certain times.
738
739```js
740function onGetCall(config) {
741 return config.method === 'get';
742}
743axios.interceptors.request.use(function (config) {
744 config.headers.test = 'special get headers';
745 return config;
746}, null, { runWhen: onGetCall });
747```
748
749### Multiple Interceptors
750
751Given you add multiple response interceptors
752and when the response was fulfilled
753- then each interceptor is executed
754- then they are executed in the order they were added
755- then only the last interceptor's result is returned
756- then every interceptor receives the result of its predecessor
757- and when the fulfillment-interceptor throws
758 - then the following fulfillment-interceptor is not called
759 - then the following rejection-interceptor is called
760 - once caught, another following fulfill-interceptor is called again (just like in a promise chain).
761
762Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code.
763
764## Handling Errors
765
766the 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.
767
768```js
769axios.get('/user/12345')
770 .catch(function (error) {
771 if (error.response) {
772 // The request was made and the server responded with a status code
773 // that falls out of the range of 2xx
774 console.log(error.response.data);
775 console.log(error.response.status);
776 console.log(error.response.headers);
777 } else if (error.request) {
778 // The request was made but no response was received
779 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
780 // http.ClientRequest in node.js
781 console.log(error.request);
782 } else {
783 // Something happened in setting up the request that triggered an Error
784 console.log('Error', error.message);
785 }
786 console.log(error.config);
787 });
788```
789
790Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error.
791
792```js
793axios.get('/user/12345', {
794 validateStatus: function (status) {
795 return status < 500; // Resolve only if the status code is less than 500
796 }
797})
798```
799
800Using `toJSON` you get an object with more information about the HTTP error.
801
802```js
803axios.get('/user/12345')
804 .catch(function (error) {
805 console.log(error.toJSON());
806 });
807```
808
809## Cancellation
810
811### AbortController
812
813Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way:
814
815```js
816const controller = new AbortController();
817
818axios.get('/foo/bar', {
819 signal: controller.signal
820}).then(function(response) {
821 //...
822});
823// cancel the request
824controller.abort()
825```
826
827### CancelToken `👎deprecated`
828
829You can also cancel a request using a *CancelToken*.
830
831> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
832
833> This API is deprecated since v0.22.0 and shouldn't be used in new projects
834
835You can create a cancel token using the `CancelToken.source` factory as shown below:
836
837```js
838const CancelToken = axios.CancelToken;
839const source = CancelToken.source();
840
841axios.get('/user/12345', {
842 cancelToken: source.token
843}).catch(function (thrown) {
844 if (axios.isCancel(thrown)) {
845 console.log('Request canceled', thrown.message);
846 } else {
847 // handle error
848 }
849});
850
851axios.post('/user/12345', {
852 name: 'new name'
853}, {
854 cancelToken: source.token
855})
856
857// cancel the request (the message parameter is optional)
858source.cancel('Operation canceled by the user.');
859```
860
861You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
862
863```js
864const CancelToken = axios.CancelToken;
865let cancel;
866
867axios.get('/user/12345', {
868 cancelToken: new CancelToken(function executor(c) {
869 // An executor function receives a cancel function as a parameter
870 cancel = c;
871 })
872});
873
874// cancel the request
875cancel();
876```
877
878> **Note:** you can cancel several requests with the same cancel token/abort controller.
879> 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.
880
881> During the transition period, you can use both cancellation APIs, even for the same request:
882
883## Using `application/x-www-form-urlencoded` format
884
885### URLSearchParams
886
887By 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).
888
889```js
890const params = new URLSearchParams({ foo: 'bar' });
891params.append('extraparam', 'value');
892axios.post('/foo', params);
893```
894
895### Query string (Older browsers)
896
897For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
898
899Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
900
901```js
902const qs = require('qs');
903axios.post('/foo', qs.stringify({ 'bar': 123 }));
904```
905
906Or in another way (ES6),
907
908```js
909import qs from 'qs';
910const data = { 'bar': 123 };
911const options = {
912 method: 'POST',
913 headers: { 'content-type': 'application/x-www-form-urlencoded' },
914 data: qs.stringify(data),
915 url,
916};
917axios(options);
918```
919
920### Older Node.js versions
921
922For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
923
924```js
925const querystring = require('querystring');
926axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
927```
928
929You can also use the [`qs`](https://github.com/ljharb/qs) library.
930
931> **Note**
932> 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.
933
934### 🆕 Automatic serialization to URLSearchParams
935
936Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
937
938```js
939const data = {
940 x: 1,
941 arr: [1, 2, 3],
942 arr2: [1, [2], 3],
943 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
944};
945
946await axios.postForm('https://postman-echo.com/post', data,
947 {headers: {'content-type': 'application/x-www-form-urlencoded'}}
948);
949```
950
951The server will handle it as:
952
953```js
954 {
955 x: '1',
956 'arr[]': [ '1', '2', '3' ],
957 'arr2[0]': '1',
958 'arr2[1][0]': '2',
959 'arr2[2]': '3',
960 'arr3[]': [ '1', '2', '3' ],
961 'users[0][name]': 'Peter',
962 'users[0][surname]': 'griffin',
963 'users[1][name]': 'Thomas',
964 'users[1][surname]': 'Anderson'
965 }
966````
967
968If 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
969
970```js
971 var app = express();
972
973 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
974
975 app.post('/', function (req, res, next) {
976 // echo body as JSON
977 res.send(JSON.stringify(req.body));
978 });
979
980 server = app.listen(3000);
981```
982
983## Using `multipart/form-data` format
984
985### FormData
986
987To send the data as a `multipart/formdata` you need to pass a formData instance as a payload.
988Setting the `Content-Type` header is not required as Axios guesses it based on the payload type.
989
990```js
991const formData = new FormData();
992formData.append('foo', 'bar');
993
994axios.post('https://httpbin.org/post', formData);
995```
996
997In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
998
999```js
1000const FormData = require('form-data');
1001
1002const form = new FormData();
1003form.append('my_field', 'my value');
1004form.append('my_buffer', new Buffer(10));
1005form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
1006
1007axios.post('https://example.com', form)
1008```
1009
1010### 🆕 Automatic serialization to FormData
1011
1012Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type`
1013header is set to `multipart/form-data`.
1014
1015The following request will submit the data in a FormData format (Browser & Node.js):
1016
1017```js
1018import axios from 'axios';
1019
1020axios.post('https://httpbin.org/post', {x: 1}, {
1021 headers: {
1022 'Content-Type': 'multipart/form-data'
1023 }
1024}).then(({data}) => console.log(data));
1025```
1026
1027In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default.
1028
1029You can overload the FormData class by setting the `env.FormData` config variable,
1030but you probably won't need it in most cases:
1031
1032```js
1033const axios = require('axios');
1034var FormData = require('form-data');
1035
1036axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, {
1037 headers: {
1038 'Content-Type': 'multipart/form-data'
1039 }
1040}).then(({data}) => console.log(data));
1041```
1042
1043Axios FormData serializer supports some special endings to perform the following operations:
1044
1045- `{}` - serialize the value with JSON.stringify
1046- `[]` - unwrap the array-like object as separate fields with the same key
1047
1048> **Note**
1049> unwrap/expand operation will be used by default on arrays and FileList objects
1050
1051FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
1052
1053- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object
1054to a `FormData` object by following custom rules.
1055
1056- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
1057
1058- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
1059The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON.
1060
1061- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects
1062
1063 - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
1064 - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
1065 - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
1066
1067Let's say we have an object like this one:
1068
1069```js
1070const obj = {
1071 x: 1,
1072 arr: [1, 2, 3],
1073 arr2: [1, [2], 3],
1074 users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
1075 'obj2{}': [{x:1}]
1076};
1077```
1078
1079The following steps will be executed by the Axios serializer internally:
1080
1081```js
1082const formData = new FormData();
1083formData.append('x', '1');
1084formData.append('arr[]', '1');
1085formData.append('arr[]', '2');
1086formData.append('arr[]', '3');
1087formData.append('arr2[0]', '1');
1088formData.append('arr2[1][0]', '2');
1089formData.append('arr2[2]', '3');
1090formData.append('users[0][name]', 'Peter');
1091formData.append('users[0][surname]', 'Griffin');
1092formData.append('users[1][name]', 'Thomas');
1093formData.append('users[1][surname]', 'Anderson');
1094formData.append('obj2{}', '[{"x":1}]');
1095```
1096
1097Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm`
1098which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`.
1099
1100## Files Posting
1101
1102You can easily submit a single file:
1103
1104```js
1105await axios.postForm('https://httpbin.org/post', {
1106 'myVar' : 'foo',
1107 'file': document.querySelector('#fileInput').files[0]
1108});
1109```
1110
1111or multiple files as `multipart/form-data`:
1112
1113```js
1114await axios.postForm('https://httpbin.org/post', {
1115 'files[]': document.querySelector('#fileInput').files
1116});
1117```
1118
1119`FileList` object can be passed directly:
1120
1121```js
1122await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
1123```
1124
1125All files will be sent with the same field names: `files[]`.
1126
1127## 🆕 HTML Form Posting (browser)
1128
1129Pass HTML Form element as a payload to submit it as `multipart/form-data` content.
1130
1131```js
1132await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
1133```
1134
1135`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
1136
1137```js
1138await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
1139 headers: {
1140 'Content-Type': 'application/json'
1141 }
1142})
1143```
1144
1145For example, the Form
1146
1147```html
1148<form id="form">
1149 <input type="text" name="foo" value="1">
1150 <input type="text" name="deep.prop" value="2">
1151 <input type="text" name="deep prop spaced" value="3">
1152 <input type="text" name="baz" value="4">
1153 <input type="text" name="baz" value="5">
1154
1155 <select name="user.age">
1156 <option value="value1">Value 1</option>
1157 <option value="value2" selected>Value 2</option>
1158 <option value="value3">Value 3</option>
1159 </select>
1160
1161 <input type="submit" value="Save">
1162</form>
1163```
1164
1165will be submitted as the following JSON object:
1166
1167```js
1168{
1169 "foo": "1",
1170 "deep": {
1171 "prop": {
1172 "spaced": "3"
1173 }
1174 },
1175 "baz": [
1176 "4",
1177 "5"
1178 ],
1179 "user": {
1180 "age": "value2"
1181 }
1182}
1183````
1184
1185Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.
1186
1187## 🆕 Progress capturing
1188
1189Axios supports both browser and node environments to capture request upload/download progress.
1190
1191```js
1192await axios.post(url, data, {
1193 onUploadProgress: function (axiosProgressEvent) {
1194 /*{
1195 loaded: number;
1196 total?: number;
1197 progress?: number; // in range [0..1]
1198 bytes: number; // how many bytes have been transferred since the last trigger (delta)
1199 estimated?: number; // estimated time in seconds
1200 rate?: number; // upload speed in bytes
1201 upload: true; // upload sign
1202 }*/
1203 },
1204
1205 onDownloadProgress: function (axiosProgressEvent) {
1206 /*{
1207 loaded: number;
1208 total?: number;
1209 progress?: number;
1210 bytes: number;
1211 estimated?: number;
1212 rate?: number; // download speed in bytes
1213 download: true; // download sign
1214 }*/
1215 }
1216});
1217```
1218
1219You can also track stream upload/download progress in node.js:
1220
1221```js
1222const {data} = await axios.post(SERVER_URL, readableStream, {
1223 onUploadProgress: ({progress}) => {
1224 console.log((progress * 100).toFixed(2));
1225 },
1226
1227 headers: {
1228 'Content-Length': contentLength
1229 },
1230
1231 maxRedirects: 0 // avoid buffering the entire stream
1232});
1233````
1234
1235> **Note:**
1236> Capturing FormData upload progress is currently not currently supported in node.js environments.
1237
1238> **⚠️ Warning**
1239> It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the **node.js** environment,
1240> as follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm.
1241
1242
1243## 🆕 Rate limiting
1244
1245Download and upload rate limits can only be set for the http adapter (node.js):
1246
1247```js
1248const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, {
1249 onUploadProgress: ({progress, rate}) => {
1250 console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`)
1251 },
1252
1253 maxRate: [100 * 1024], // 100KB/s limit
1254});
1255```
1256
1257## Semver
1258
1259Until 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.
1260
1261## Promises
1262
1263axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises).
1264If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
1265
1266## TypeScript
1267
1268axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors.
1269
1270```typescript
1271let user: User = null;
1272try {
1273 const { data } = await axios.get('/user?ID=12345');
1274 user = data.userDetails;
1275} catch (error) {
1276 if (axios.isAxiosError(error)) {
1277 handleAxiosError(error);
1278 } else {
1279 handleUnexpectedError(error);
1280 }
1281}
1282```
1283
1284Because axios dual publishes with an ESM default export and a CJS `module.exports`, there are some caveats.
1285The recommended setting is to use `"moduleResolution": "node16"` (this is implied by `"module": "node16"`). Note that this requires TypeScript 4.7 or greater.
1286If use ESM, your settings should be fine.
1287If you compile TypeScript to CJS and you can’t use `"moduleResolution": "node 16"`, you have to enable `esModuleInterop`.
1288If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`.
1289
1290## Online one-click setup
1291
1292You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online.
1293
1294[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js)
1295
1296
1297## Resources
1298
1299* [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
1300* [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
1301* [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
1302* [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md)
1303
1304## Credits
1305
1306axios 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.
1307
1308## License
1309
1310[MIT](LICENSE)