1# axios
2
3[](https://www.npmjs.org/package/axios)
4[](https://cdnjs.com/libraries/axios)
5
6[](https://gitpod.io/#https://github.com/axios/axios)
7[](https://coveralls.io/r/mzabriskie/axios)
8[](https://packagephobia.now.sh/result?p=axios)
9[](http://npm-stat.com/charts.html?package=axios)
10[](https://gitter.im/mzabriskie/axios)
11[](https://www.codetriage.com/axios/axios)
12
13Promise based HTTP client for the browser and node.js
14
15> New axios docs website: [click here](https://axios-http.com/)
16
17## Table of Contents
18
19 - [Features](#features)
20 - [Browser Support](#browser-support)
21 - [Installing](#installing)
22 - [Example](#example)
23 - [Axios API](#axios-api)
24 - [Request method aliases](#request-method-aliases)
25 - [Concurrency (Deprecated)](#concurrency-deprecated)
26 - [Creating an instance](#creating-an-instance)
27 - [Instance methods](#instance-methods)
28 - [Request Config](#request-config)
29 - [Response Schema](#response-schema)
30 - [Config Defaults](#config-defaults)
31 - [Global axios defaults](#global-axios-defaults)
32 - [Custom instance defaults](#custom-instance-defaults)
33 - [Config order of precedence](#config-order-of-precedence)
34 - [Interceptors](#interceptors)
35 - [Handling Errors](#handling-errors)
36 - [Cancellation](#cancellation)
37 - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
38 - [Browser](#browser)
39 - [Node.js](#nodejs)
40 - [Query string](#query-string)
41 - [Form data](#form-data)
42 - [Semver](#semver)
43 - [Promises](#promises)
44 - [TypeScript](#typescript)
45 - [Resources](#resources)
46 - [Credits](#credits)
47 - [License](#license)
48
49## Features
50
51- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
52- Make [http](http://nodejs.org/api/http.html) requests from node.js
53- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
54- Intercept request and response
55- Transform request and response data
56- Cancel requests
57- Automatic transforms for JSON data
58- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
59
60## Browser Support
61
62 |  |  |  |  |  |
63--- | --- | --- | --- | --- | --- |
64Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
65
66[](https://saucelabs.com/u/axios)
67
68## Installing
69
70Using npm:
71
72```bash
73$ npm install axios
74```
75
76Using bower:
77
78```bash
79$ bower install axios
80```
81
82Using yarn:
83
84```bash
85$ yarn add axios
86```
87
88Using jsDelivr CDN:
89
90```html
91<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
92```
93
94Using unpkg CDN:
95
96```html
97<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
98```
99
100## Example
101
102### note: CommonJS usage
103In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
104
105```js
106const axios = require('axios').default;
107
108// axios.<method> will now provide autocomplete and parameter typings
109```
110
111Performing a `GET` request
112
113```js
114const axios = require('axios');
115
116// Make a request for a user with a given ID
117axios.get('/user?ID=12345')
118 .then(function (response) {
119 // handle success
120 console.log(response);
121 })
122 .catch(function (error) {
123 // handle error
124 console.log(error);
125 })
126 .then(function () {
127 // always executed
128 });
129
130// Optionally the request above could also be done as
131axios.get('/user', {
132 params: {
133 ID: 12345
134 }
135 })
136 .then(function (response) {
137 console.log(response);
138 })
139 .catch(function (error) {
140 console.log(error);
141 })
142 .then(function () {
143 // always executed
144 });
145
146// Want to use async/await? Add the `async` keyword to your outer function/method.
147async function getUser() {
148 try {
149 const response = await axios.get('/user?ID=12345');
150 console.log(response);
151 } catch (error) {
152 console.error(error);
153 }
154}
155```
156
157> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
158> Explorer and older browsers, so use with caution.
159
160Performing a `POST` request
161
162```js
163axios.post('/user', {
164 firstName: 'Fred',
165 lastName: 'Flintstone'
166 })
167 .then(function (response) {
168 console.log(response);
169 })
170 .catch(function (error) {
171 console.log(error);
172 });
173```
174
175Performing multiple concurrent requests
176
177```js
178function getUserAccount() {
179 return axios.get('/user/12345');
180}
181
182function getUserPermissions() {
183 return axios.get('/user/12345/permissions');
184}
185
186Promise.all([getUserAccount(), getUserPermissions()])
187 .then(function (results) {
188 const acct = results[0];
189 const perm = results[1];
190 });
191```
192
193## axios API
194
195Requests can be made by passing the relevant config to `axios`.
196
197##### axios(config)
198
199```js
200// Send a POST request
201axios({
202 method: 'post',
203 url: '/user/12345',
204 data: {
205 firstName: 'Fred',
206 lastName: 'Flintstone'
207 }
208});
209```
210
211```js
212// GET request for remote image in node.js
213axios({
214 method: 'get',
215 url: 'http://bit.ly/2mTM3nY',
216 responseType: 'stream'
217})
218 .then(function (response) {
219 response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
220 });
221```
222
223##### axios(url[, config])
224
225```js
226// Send a GET request (default method)
227axios('/user/12345');
228```
229
230### Request method aliases
231
232For convenience aliases have been provided for all supported request methods.
233
234##### axios.request(config)
235##### axios.get(url[, config])
236##### axios.delete(url[, config])
237##### axios.head(url[, config])
238##### axios.options(url[, config])
239##### axios.post(url[, data[, config]])
240##### axios.put(url[, data[, config]])
241##### axios.patch(url[, data[, config]])
242
243###### NOTE
244When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
245
246### Concurrency (Deprecated)
247Please use `Promise.all` to replace the below functions.
248
249Helper functions for dealing with concurrent requests.
250
251axios.all(iterable)
252axios.spread(callback)
253
254### Creating an instance
255
256You can create a new instance of axios with a custom config.
257
258##### axios.create([config])
259
260```js
261const instance = axios.create({
262 baseURL: 'https://some-domain.com/api/',
263 timeout: 1000,
264 headers: {'X-Custom-Header': 'foobar'}
265});
266```
267
268### Instance methods
269
270The available instance methods are listed below. The specified config will be merged with the instance config.
271
272##### axios#request(config)
273##### axios#get(url[, config])
274##### axios#delete(url[, config])
275##### axios#head(url[, config])
276##### axios#options(url[, config])
277##### axios#post(url[, data[, config]])
278##### axios#put(url[, data[, config]])
279##### axios#patch(url[, data[, config]])
280##### axios#getUri([config])
281
282## Request Config
283
284These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
285
286```js
287{
288 // `url` is the server URL that will be used for the request
289 url: '/user',
290
291 // `method` is the request method to be used when making the request
292 method: 'get', // default
293
294 // `baseURL` will be prepended to `url` unless `url` is absolute.
295 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
296 // to methods of that instance.
297 baseURL: 'https://some-domain.com/api/',
298
299 // `transformRequest` allows changes to the request data before it is sent to the server
300 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
301 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
302 // FormData or Stream
303 // You may modify the headers object.
304 transformRequest: [function (data, headers) {
305 // Do whatever you want to transform the data
306
307 return data;
308 }],
309
310 // `transformResponse` allows changes to the response data to be made before
311 // it is passed to then/catch
312 transformResponse: [function (data) {
313 // Do whatever you want to transform the data
314
315 return data;
316 }],
317
318 // `headers` are custom headers to be sent
319 headers: {'X-Requested-With': 'XMLHttpRequest'},
320
321 // `params` are the URL parameters to be sent with the request
322 // Must be a plain object or a URLSearchParams object
323 params: {
324 ID: 12345
325 },
326
327 // `paramsSerializer` is an optional function in charge of serializing `params`
328 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
329 paramsSerializer: function (params) {
330 return Qs.stringify(params, {arrayFormat: 'brackets'})
331 },
332
333 // `data` is the data to be sent as the request body
334 // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
335 // When no `transformRequest` is set, must be of one of the following types:
336 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
337 // - Browser only: FormData, File, Blob
338 // - Node only: Stream, Buffer
339 data: {
340 firstName: 'Fred'
341 },
342
343 // syntax alternative to send data into the body
344 // method post
345 // only the value is sent, not the key
346 data: 'Country=Brasil&City=Belo Horizonte',
347
348 // `timeout` specifies the number of milliseconds before the request times out.
349 // If the request takes longer than `timeout`, the request will be aborted.
350 timeout: 1000, // default is `0` (no timeout)
351
352 // `withCredentials` indicates whether or not cross-site Access-Control requests
353 // should be made using credentials
354 withCredentials: false, // default
355
356 // `adapter` allows custom handling of requests which makes testing easier.
357 // Return a promise and supply a valid response (see lib/adapters/README.md).
358 adapter: function (config) {
359 /* ... */
360 },
361
362 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
363 // This will set an `Authorization` header, overwriting any existing
364 // `Authorization` custom headers you have set using `headers`.
365 // Please note that only HTTP Basic auth is configurable through this parameter.
366 // For Bearer tokens and such, use `Authorization` custom headers instead.
367 auth: {
368 username: 'janedoe',
369 password: 's00pers3cret'
370 },
371
372 // `responseType` indicates the type of data that the server will respond with
373 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
374 // browser only: 'blob'
375 responseType: 'json', // default
376
377 // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
378 // Note: Ignored for `responseType` of 'stream' or client-side requests
379 responseEncoding: 'utf8', // default
380
381 // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
382 xsrfCookieName: 'XSRF-TOKEN', // default
383
384 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
385 xsrfHeaderName: 'X-XSRF-TOKEN', // default
386
387 // `onUploadProgress` allows handling of progress events for uploads
388 // browser only
389 onUploadProgress: function (progressEvent) {
390 // Do whatever you want with the native progress event
391 },
392
393 // `onDownloadProgress` allows handling of progress events for downloads
394 // browser only
395 onDownloadProgress: function (progressEvent) {
396 // Do whatever you want with the native progress event
397 },
398
399 // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
400 maxContentLength: 2000,
401
402 // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
403 maxBodyLength: 2000,
404
405 // `validateStatus` defines whether to resolve or reject the promise for a given
406 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
407 // or `undefined`), the promise will be resolved; otherwise, the promise will be
408 // rejected.
409 validateStatus: function (status) {
410 return status >= 200 && status < 300; // default
411 },
412
413 // `maxRedirects` defines the maximum number of redirects to follow in node.js.
414 // If set to 0, no redirects will be followed.
415 maxRedirects: 5, // default
416
417 // `socketPath` defines a UNIX Socket to be used in node.js.
418 // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
419 // Only either `socketPath` or `proxy` can be specified.
420 // If both are specified, `socketPath` is used.
421 socketPath: null, // default
422
423 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
424 // and https requests, respectively, in node.js. This allows options to be added like
425 // `keepAlive` that are not enabled by default.
426 httpAgent: new http.Agent({ keepAlive: true }),
427 httpsAgent: new https.Agent({ keepAlive: true }),
428
429 // `proxy` defines the hostname, port, and protocol of the proxy server.
430 // You can also define your proxy using the conventional `http_proxy` and
431 // `https_proxy` environment variables. If you are using environment variables
432 // for your proxy configuration, you can also define a `no_proxy` environment
433 // variable as a comma-separated list of domains that should not be proxied.
434 // Use `false` to disable proxies, ignoring environment variables.
435 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
436 // supplies credentials.
437 // This will set an `Proxy-Authorization` header, overwriting any existing
438 // `Proxy-Authorization` custom headers you have set using `headers`.
439 // If the proxy server uses HTTPS, then you must set the protocol to `https`.
440 proxy: {
441 protocol: 'https',
442 host: '127.0.0.1',
443 port: 9000,
444 auth: {
445 username: 'mikeymike',
446 password: 'rapunz3l'
447 }
448 },
449
450 // `cancelToken` specifies a cancel token that can be used to cancel the request
451 // (see Cancellation section below for details)
452 cancelToken: new CancelToken(function (cancel) {
453 }),
454
455 // an alternative way to cancel Axios requests using AbortController
456 signal: new AbortController().signal,
457
458 // `decompress` indicates whether or not the response body should be decompressed
459 // automatically. If set to `true` will also remove the 'content-encoding' header
460 // from the responses objects of all decompressed responses
461 // - Node only (XHR cannot turn off decompression)
462 decompress: true // default
463
464 // `insecureHTTPParser` boolean.
465 // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
466 // This may allow interoperability with non-conformant HTTP implementations.
467 // Using the insecure parser should be avoided.
468 // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
469 // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
470 insecureHTTPParser: undefined // default
471
472 // transitional options for backward compatibility that may be removed in the newer versions
473 transitional: {
474 // silent JSON parsing mode
475 // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
476 // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
477 silentJSONParsing: true, // default value for the current Axios version
478
479 // try to parse the response string as JSON even if `responseType` is not 'json'
480 forcedJSONParsing: true,
481
482 // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
483 clarifyTimeoutError: false,
484 }
485}
486```
487
488## Response Schema
489
490The response for a request contains the following information.
491
492```js
493{
494 // `data` is the response that was provided by the server
495 data: {},
496
497 // `status` is the HTTP status code from the server response
498 status: 200,
499
500 // `statusText` is the HTTP status message from the server response
501 statusText: 'OK',
502
503 // `headers` the HTTP headers that the server responded with
504 // All header names are lower cased and can be accessed using the bracket notation.
505 // Example: `response.headers['content-type']`
506 headers: {},
507
508 // `config` is the config that was provided to `axios` for the request
509 config: {},
510
511 // `request` is the request that generated this response
512 // It is the last ClientRequest instance in node.js (in redirects)
513 // and an XMLHttpRequest instance in the browser
514 request: {}
515}
516```
517
518When using `then`, you will receive the response as follows:
519
520```js
521axios.get('/user/12345')
522 .then(function (response) {
523 console.log(response.data);
524 console.log(response.status);
525 console.log(response.statusText);
526 console.log(response.headers);
527 console.log(response.config);
528 });
529```
530
531When 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.
532
533## Config Defaults
534
535You can specify config defaults that will be applied to every request.
536
537### Global axios defaults
538
539```js
540axios.defaults.baseURL = 'https://api.example.com';
541
542// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
543// See below for an example using Custom instance defaults instead.
544axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
545
546axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
547```
548
549### Custom instance defaults
550
551```js
552// Set config defaults when creating the instance
553const instance = axios.create({
554 baseURL: 'https://api.example.com'
555});
556
557// Alter defaults after instance has been created
558instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
559```
560
561### Config order of precedence
562
563Config 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.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.
564
565```js
566// Create an instance using the config defaults provided by the library
567// At this point the timeout config value is `0` as is the default for the library
568const instance = axios.create();
569
570// Override timeout default for the library
571// Now all requests using this instance will wait 2.5 seconds before timing out
572instance.defaults.timeout = 2500;
573
574// Override timeout for this request as it's known to take a long time
575instance.get('/longRequest', {
576 timeout: 5000
577});
578```
579
580## Interceptors
581
582You can intercept requests or responses before they are handled by `then` or `catch`.
583
584```js
585// Add a request interceptor
586axios.interceptors.request.use(function (config) {
587 // Do something before request is sent
588 return config;
589 }, function (error) {
590 // Do something with request error
591 return Promise.reject(error);
592 });
593
594// Add a response interceptor
595axios.interceptors.response.use(function (response) {
596 // Any status code that lie within the range of 2xx cause this function to trigger
597 // Do something with response data
598 return response;
599 }, function (error) {
600 // Any status codes that falls outside the range of 2xx cause this function to trigger
601 // Do something with response error
602 return Promise.reject(error);
603 });
604```
605
606If you need to remove an interceptor later you can.
607
608```js
609const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
610axios.interceptors.request.eject(myInterceptor);
611```
612
613You can add interceptors to a custom instance of axios.
614
615```js
616const instance = axios.create();
617instance.interceptors.request.use(function () {/*...*/});
618```
619
620When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
621in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
622the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
623to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
624
625```js
626axios.interceptors.request.use(function (config) {
627 config.headers.test = 'I am only a header!';
628 return config;
629}, null, { synchronous: true });
630```
631
632If you want to execute a particular interceptor based on a runtime check,
633you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return
634of `runWhen` is `false`. The function will be called with the config
635object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
636asynchronous request interceptor that only needs to run at certain times.
637
638```js
639function onGetCall(config) {
640 return config.method === 'get';
641}
642axios.interceptors.request.use(function (config) {
643 config.headers.test = 'special get headers';
644 return config;
645}, null, { runWhen: onGetCall });
646```
647
648## Handling Errors
649
650```js
651axios.get('/user/12345')
652 .catch(function (error) {
653 if (error.response) {
654 // The request was made and the server responded with a status code
655 // that falls out of the range of 2xx
656 console.log(error.response.data);
657 console.log(error.response.status);
658 console.log(error.response.headers);
659 } else if (error.request) {
660 // The request was made but no response was received
661 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
662 // http.ClientRequest in node.js
663 console.log(error.request);
664 } else {
665 // Something happened in setting up the request that triggered an Error
666 console.log('Error', error.message);
667 }
668 console.log(error.config);
669 });
670```
671
672Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
673
674```js
675axios.get('/user/12345', {
676 validateStatus: function (status) {
677 return status < 500; // Resolve only if the status code is less than 500
678 }
679})
680```
681
682Using `toJSON` you get an object with more information about the HTTP error.
683
684```js
685axios.get('/user/12345')
686 .catch(function (error) {
687 console.log(error.toJSON());
688 });
689```
690
691## Cancellation
692
693You can cancel a request using a *cancel token*.
694
695> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
696
697You can create a cancel token using the `CancelToken.source` factory as shown below:
698
699```js
700const CancelToken = axios.CancelToken;
701const source = CancelToken.source();
702
703axios.get('/user/12345', {
704 cancelToken: source.token
705}).catch(function (thrown) {
706 if (axios.isCancel(thrown)) {
707 console.log('Request canceled', thrown.message);
708 } else {
709 // handle error
710 }
711});
712
713axios.post('/user/12345', {
714 name: 'new name'
715}, {
716 cancelToken: source.token
717})
718
719// cancel the request (the message parameter is optional)
720source.cancel('Operation canceled by the user.');
721```
722
723You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
724
725```js
726const CancelToken = axios.CancelToken;
727let cancel;
728
729axios.get('/user/12345', {
730 cancelToken: new CancelToken(function executor(c) {
731 // An executor function receives a cancel function as a parameter
732 cancel = c;
733 })
734});
735
736// cancel the request
737cancel();
738```
739
740Axios supports AbortController to abort requests in [`fetch API`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#aborting_a_fetch) way:
741```js
742const controller = new AbortController();
743
744axios.get('/foo/bar', {
745 signal: controller.signal
746}).then(function(response) {
747 //...
748});
749// cancel the request
750controller.abort()
751```
752
753> Note: you can cancel several requests with the same cancel token/abort controller.
754> 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 real request.
755
756## Using application/x-www-form-urlencoded format
757
758By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.
759
760### Browser
761
762In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
763
764```js
765const params = new URLSearchParams();
766params.append('param1', 'value1');
767params.append('param2', 'value2');
768axios.post('/foo', params);
769```
770
771> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
772
773Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
774
775```js
776const qs = require('qs');
777axios.post('/foo', qs.stringify({ 'bar': 123 }));
778```
779
780Or in another way (ES6),
781
782```js
783import qs from 'qs';
784const data = { 'bar': 123 };
785const options = {
786 method: 'POST',
787 headers: { 'content-type': 'application/x-www-form-urlencoded' },
788 data: qs.stringify(data),
789 url,
790};
791axios(options);
792```
793
794### Node.js
795
796#### Query string
797
798In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
799
800```js
801const querystring = require('querystring');
802axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
803```
804
805or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows:
806
807```js
808const url = require('url');
809const params = new url.URLSearchParams({ foo: 'bar' });
810axios.post('http://something.com/', params.toString());
811```
812
813You can also use the [`qs`](https://github.com/ljharb/qs) library.
814
815###### NOTE
816The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
817
818#### Form data
819
820In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
821
822```js
823const FormData = require('form-data');
824
825const form = new FormData();
826form.append('my_field', 'my value');
827form.append('my_buffer', new Buffer(10));
828form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
829
830axios.post('https://example.com', form, { headers: form.getHeaders() })
831```
832
833Alternatively, use an interceptor:
834
835```js
836axios.interceptors.request.use(config => {
837 if (config.data instanceof FormData) {
838 Object.assign(config.headers, config.data.getHeaders());
839 }
840 return config;
841});
842```
843
844## Semver
845
846Until 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.
847
848## Promises
849
850axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
851If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
852
853## TypeScript
854
855axios includes [TypeScript](http://typescriptlang.org) definitions and a type guard for axios errors.
856
857```typescript
858let user: User = null;
859try {
860 const { data } = await axios.get('/user?ID=12345');
861 user = data.userDetails;
862} catch (error) {
863 if (axios.isAxiosError(error)) {
864 handleAxiosError(error);
865 } else {
866 handleUnexpectedError(error);
867 }
868}
869```
870
871## Online one-click setup
872
873You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online.
874
875[](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js)
876
877
878## Resources
879
880* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
881* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
882* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
883* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
884* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
885
886## Credits
887
888axios 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.
889
890## License
891
892[MIT](LICENSE)