UNPKG

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