You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

798 lines
25 KiB

  1. # axios
  2. [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
  3. [![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
  4. [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios)
  5. [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
  6. [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios)
  7. [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios)
  8. [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
  9. [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
  10. Promise based HTTP client for the browser and node.js
  11. ## Table of Contents
  12. - [Features](#features)
  13. - [Browser Support](#browser-support)
  14. - [Installing](#installing)
  15. - [Example](#example)
  16. - [Axios API](#axios-api)
  17. - [Request method aliases](#request-method-aliases)
  18. - [Concurrency (Deprecated)](#concurrency-deprecated)
  19. - [Creating an instance](#creating-an-instance)
  20. - [Instance methods](#instance-methods)
  21. - [Request Config](#request-config)
  22. - [Response Schema](#response-schema)
  23. - [Config Defaults](#config-defaults)
  24. - [Global axios defaults](#global-axios-defaults)
  25. - [Custom instance defaults](#custom-instance-defaults)
  26. - [Config order of precedence](#config-order-of-precedence)
  27. - [Interceptors](#interceptors)
  28. - [Handling Errors](#handling-errors)
  29. - [Cancellation](#cancellation)
  30. - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
  31. - [Browser](#browser)
  32. - [Node.js](#nodejs)
  33. - [Query string](#query-string)
  34. - [Form data](#form-data)
  35. - [Semver](#semver)
  36. - [Promises](#promises)
  37. - [TypeScript](#typescript)
  38. - [Resources](#resources)
  39. - [Credits](#credits)
  40. - [License](#license)
  41. ## Features
  42. - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
  43. - Make [http](http://nodejs.org/api/http.html) requests from node.js
  44. - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
  45. - Intercept request and response
  46. - Transform request and response data
  47. - Cancel requests
  48. - Automatic transforms for JSON data
  49. - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  50. ## Browser Support
  51. ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) |
  52. --- | --- | --- | --- | --- | --- |
  53. Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
  54. [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
  55. ## Installing
  56. Using npm:
  57. ```bash
  58. $ npm install axios
  59. ```
  60. Using bower:
  61. ```bash
  62. $ bower install axios
  63. ```
  64. Using yarn:
  65. ```bash
  66. $ yarn add axios
  67. ```
  68. Using jsDelivr CDN:
  69. ```html
  70. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  71. ```
  72. Using unpkg CDN:
  73. ```html
  74. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  75. ```
  76. ## Example
  77. ### note: CommonJS usage
  78. In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
  79. ```js
  80. const axios = require('axios').default;
  81. // axios.<method> will now provide autocomplete and parameter typings
  82. ```
  83. Performing a `GET` request
  84. ```js
  85. const axios = require('axios');
  86. // Make a request for a user with a given ID
  87. axios.get('/user?ID=12345')
  88. .then(function (response) {
  89. // handle success
  90. console.log(response);
  91. })
  92. .catch(function (error) {
  93. // handle error
  94. console.log(error);
  95. })
  96. .then(function () {
  97. // always executed
  98. });
  99. // Optionally the request above could also be done as
  100. axios.get('/user', {
  101. params: {
  102. ID: 12345
  103. }
  104. })
  105. .then(function (response) {
  106. console.log(response);
  107. })
  108. .catch(function (error) {
  109. console.log(error);
  110. })
  111. .then(function () {
  112. // always executed
  113. });
  114. // Want to use async/await? Add the `async` keyword to your outer function/method.
  115. async function getUser() {
  116. try {
  117. const response = await axios.get('/user?ID=12345');
  118. console.log(response);
  119. } catch (error) {
  120. console.error(error);
  121. }
  122. }
  123. ```
  124. > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
  125. > Explorer and older browsers, so use with caution.
  126. Performing a `POST` request
  127. ```js
  128. axios.post('/user', {
  129. firstName: 'Fred',
  130. lastName: 'Flintstone'
  131. })
  132. .then(function (response) {
  133. console.log(response);
  134. })
  135. .catch(function (error) {
  136. console.log(error);
  137. });
  138. ```
  139. Performing multiple concurrent requests
  140. ```js
  141. function getUserAccount() {
  142. return axios.get('/user/12345');
  143. }
  144. function getUserPermissions() {
  145. return axios.get('/user/12345/permissions');
  146. }
  147. Promise.all([getUserAccount(), getUserPermissions()])
  148. .then(function (results) {
  149. const acct = results[0];
  150. const perm = results[1];
  151. });
  152. ```
  153. ## axios API
  154. Requests can be made by passing the relevant config to `axios`.
  155. ##### axios(config)
  156. ```js
  157. // Send a POST request
  158. axios({
  159. method: 'post',
  160. url: '/user/12345',
  161. data: {
  162. firstName: 'Fred',
  163. lastName: 'Flintstone'
  164. }
  165. });
  166. ```
  167. ```js
  168. // GET request for remote image in node.js
  169. axios({
  170. method: 'get',
  171. url: 'http://bit.ly/2mTM3nY',
  172. responseType: 'stream'
  173. })
  174. .then(function (response) {
  175. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  176. });
  177. ```
  178. ##### axios(url[, config])
  179. ```js
  180. // Send a GET request (default method)
  181. axios('/user/12345');
  182. ```
  183. ### Request method aliases
  184. For convenience aliases have been provided for all supported request methods.
  185. ##### axios.request(config)
  186. ##### axios.get(url[, config])
  187. ##### axios.delete(url[, config])
  188. ##### axios.head(url[, config])
  189. ##### axios.options(url[, config])
  190. ##### axios.post(url[, data[, config]])
  191. ##### axios.put(url[, data[, config]])
  192. ##### axios.patch(url[, data[, config]])
  193. ###### NOTE
  194. When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
  195. ### Concurrency (Deprecated)
  196. Please use `Promise.all` to replace the below functions.
  197. Helper functions for dealing with concurrent requests.
  198. axios.all(iterable)
  199. axios.spread(callback)
  200. ### Creating an instance
  201. You can create a new instance of axios with a custom config.
  202. ##### axios.create([config])
  203. ```js
  204. const instance = axios.create({
  205. baseURL: 'https://some-domain.com/api/',
  206. timeout: 1000,
  207. headers: {'X-Custom-Header': 'foobar'}
  208. });
  209. ```
  210. ### Instance methods
  211. The available instance methods are listed below. The specified config will be merged with the instance config.
  212. ##### axios#request(config)
  213. ##### axios#get(url[, config])
  214. ##### axios#delete(url[, config])
  215. ##### axios#head(url[, config])
  216. ##### axios#options(url[, config])
  217. ##### axios#post(url[, data[, config]])
  218. ##### axios#put(url[, data[, config]])
  219. ##### axios#patch(url[, data[, config]])
  220. ##### axios#getUri([config])
  221. ## Request Config
  222. These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
  223. ```js
  224. {
  225. // `url` is the server URL that will be used for the request
  226. url: '/user',
  227. // `method` is the request method to be used when making the request
  228. method: 'get', // default
  229. // `baseURL` will be prepended to `url` unless `url` is absolute.
  230. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  231. // to methods of that instance.
  232. baseURL: 'https://some-domain.com/api/',
  233. // `transformRequest` allows changes to the request data before it is sent to the server
  234. // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  235. // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  236. // FormData or Stream
  237. // You may modify the headers object.
  238. transformRequest: [function (data, headers) {
  239. // Do whatever you want to transform the data
  240. return data;
  241. }],
  242. // `transformResponse` allows changes to the response data to be made before
  243. // it is passed to then/catch
  244. transformResponse: [function (data) {
  245. // Do whatever you want to transform the data
  246. return data;
  247. }],
  248. // `headers` are custom headers to be sent
  249. headers: {'X-Requested-With': 'XMLHttpRequest'},
  250. // `params` are the URL parameters to be sent with the request
  251. // Must be a plain object or a URLSearchParams object
  252. params: {
  253. ID: 12345
  254. },
  255. // `paramsSerializer` is an optional function in charge of serializing `params`
  256. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  257. paramsSerializer: function (params) {
  258. return Qs.stringify(params, {arrayFormat: 'brackets'})
  259. },
  260. // `data` is the data to be sent as the request body
  261. // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  262. // When no `transformRequest` is set, must be of one of the following types:
  263. // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  264. // - Browser only: FormData, File, Blob
  265. // - Node only: Stream, Buffer
  266. data: {
  267. firstName: 'Fred'
  268. },
  269. // syntax alternative to send data into the body
  270. // method post
  271. // only the value is sent, not the key
  272. data: 'Country=Brasil&City=Belo Horizonte',
  273. // `timeout` specifies the number of milliseconds before the request times out.
  274. // If the request takes longer than `timeout`, the request will be aborted.
  275. timeout: 1000, // default is `0` (no timeout)
  276. // `withCredentials` indicates whether or not cross-site Access-Control requests
  277. // should be made using credentials
  278. withCredentials: false, // default
  279. // `adapter` allows custom handling of requests which makes testing easier.
  280. // Return a promise and supply a valid response (see lib/adapters/README.md).
  281. adapter: function (config) {
  282. /* ... */
  283. },
  284. // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  285. // This will set an `Authorization` header, overwriting any existing
  286. // `Authorization` custom headers you have set using `headers`.
  287. // Please note that only HTTP Basic auth is configurable through this parameter.
  288. // For Bearer tokens and such, use `Authorization` custom headers instead.
  289. auth: {
  290. username: 'janedoe',
  291. password: 's00pers3cret'
  292. },
  293. // `responseType` indicates the type of data that the server will respond with
  294. // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  295. // browser only: 'blob'
  296. responseType: 'json', // default
  297. // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
  298. // Note: Ignored for `responseType` of 'stream' or client-side requests
  299. responseEncoding: 'utf8', // default
  300. // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  301. xsrfCookieName: 'XSRF-TOKEN', // default
  302. // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  303. xsrfHeaderName: 'X-XSRF-TOKEN', // default
  304. // `onUploadProgress` allows handling of progress events for uploads
  305. // browser only
  306. onUploadProgress: function (progressEvent) {
  307. // Do whatever you want with the native progress event
  308. },
  309. // `onDownloadProgress` allows handling of progress events for downloads
  310. // browser only
  311. onDownloadProgress: function (progressEvent) {
  312. // Do whatever you want with the native progress event
  313. },
  314. // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
  315. maxContentLength: 2000,
  316. // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  317. maxBodyLength: 2000,
  318. // `validateStatus` defines whether to resolve or reject the promise for a given
  319. // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  320. // or `undefined`), the promise will be resolved; otherwise, the promise will be
  321. // rejected.
  322. validateStatus: function (status) {
  323. return status >= 200 && status < 300; // default
  324. },
  325. // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  326. // If set to 0, no redirects will be followed.
  327. maxRedirects: 5, // default
  328. // `socketPath` defines a UNIX Socket to be used in node.js.
  329. // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  330. // Only either `socketPath` or `proxy` can be specified.
  331. // If both are specified, `socketPath` is used.
  332. socketPath: null, // default
  333. // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  334. // and https requests, respectively, in node.js. This allows options to be added like
  335. // `keepAlive` that are not enabled by default.
  336. httpAgent: new http.Agent({ keepAlive: true }),
  337. httpsAgent: new https.Agent({ keepAlive: true }),
  338. // `proxy` defines the hostname and port of the proxy server.
  339. // You can also define your proxy using the conventional `http_proxy` and
  340. // `https_proxy` environment variables. If you are using environment variables
  341. // for your proxy configuration, you can also define a `no_proxy` environment
  342. // variable as a comma-separated list of domains that should not be proxied.
  343. // Use `false` to disable proxies, ignoring environment variables.
  344. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  345. // supplies credentials.
  346. // This will set an `Proxy-Authorization` header, overwriting any existing
  347. // `Proxy-Authorization` custom headers you have set using `headers`.
  348. proxy: {
  349. host: '127.0.0.1',
  350. port: 9000,
  351. auth: {
  352. username: 'mikeymike',
  353. password: 'rapunz3l'
  354. }
  355. },
  356. // `cancelToken` specifies a cancel token that can be used to cancel the request
  357. // (see Cancellation section below for details)
  358. cancelToken: new CancelToken(function (cancel) {
  359. }),
  360. // `decompress` indicates whether or not the response body should be decompressed
  361. // automatically. If set to `true` will also remove the 'content-encoding' header
  362. // from the responses objects of all decompressed responses
  363. // - Node only (XHR cannot turn off decompression)
  364. decompress: true // default
  365. }
  366. ```
  367. ## Response Schema
  368. The response for a request contains the following information.
  369. ```js
  370. {
  371. // `data` is the response that was provided by the server
  372. data: {},
  373. // `status` is the HTTP status code from the server response
  374. status: 200,
  375. // `statusText` is the HTTP status message from the server response
  376. statusText: 'OK',
  377. // `headers` the HTTP headers that the server responded with
  378. // All header names are lower cased and can be accessed using the bracket notation.
  379. // Example: `response.headers['content-type']`
  380. headers: {},
  381. // `config` is the config that was provided to `axios` for the request
  382. config: {},
  383. // `request` is the request that generated this response
  384. // It is the last ClientRequest instance in node.js (in redirects)
  385. // and an XMLHttpRequest instance in the browser
  386. request: {}
  387. }
  388. ```
  389. When using `then`, you will receive the response as follows:
  390. ```js
  391. axios.get('/user/12345')
  392. .then(function (response) {
  393. console.log(response.data);
  394. console.log(response.status);
  395. console.log(response.statusText);
  396. console.log(response.headers);
  397. console.log(response.config);
  398. });
  399. ```
  400. When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.
  401. ## Config Defaults
  402. You can specify config defaults that will be applied to every request.
  403. ### Global axios defaults
  404. ```js
  405. axios.defaults.baseURL = 'https://api.example.com';
  406. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  407. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  408. ```
  409. ### Custom instance defaults
  410. ```js
  411. // Set config defaults when creating the instance
  412. const instance = axios.create({
  413. baseURL: 'https://api.example.com'
  414. });
  415. // Alter defaults after instance has been created
  416. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  417. ```
  418. ### Config order of precedence
  419. Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.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.
  420. ```js
  421. // Create an instance using the config defaults provided by the library
  422. // At this point the timeout config value is `0` as is the default for the library
  423. const instance = axios.create();
  424. // Override timeout default for the library
  425. // Now all requests using this instance will wait 2.5 seconds before timing out
  426. instance.defaults.timeout = 2500;
  427. // Override timeout for this request as it's known to take a long time
  428. instance.get('/longRequest', {
  429. timeout: 5000
  430. });
  431. ```
  432. ## Interceptors
  433. You can intercept requests or responses before they are handled by `then` or `catch`.
  434. ```js
  435. // Add a request interceptor
  436. axios.interceptors.request.use(function (config) {
  437. // Do something before request is sent
  438. return config;
  439. }, function (error) {
  440. // Do something with request error
  441. return Promise.reject(error);
  442. });
  443. // Add a response interceptor
  444. axios.interceptors.response.use(function (response) {
  445. // Any status code that lie within the range of 2xx cause this function to trigger
  446. // Do something with response data
  447. return response;
  448. }, function (error) {
  449. // Any status codes that falls outside the range of 2xx cause this function to trigger
  450. // Do something with response error
  451. return Promise.reject(error);
  452. });
  453. ```
  454. If you need to remove an interceptor later you can.
  455. ```js
  456. const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
  457. axios.interceptors.request.eject(myInterceptor);
  458. ```
  459. You can add interceptors to a custom instance of axios.
  460. ```js
  461. const instance = axios.create();
  462. instance.interceptors.request.use(function () {/*...*/});
  463. ```
  464. ## Handling Errors
  465. ```js
  466. axios.get('/user/12345')
  467. .catch(function (error) {
  468. if (error.response) {
  469. // The request was made and the server responded with a status code
  470. // that falls out of the range of 2xx
  471. console.log(error.response.data);
  472. console.log(error.response.status);
  473. console.log(error.response.headers);
  474. } else if (error.request) {
  475. // The request was made but no response was received
  476. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  477. // http.ClientRequest in node.js
  478. console.log(error.request);
  479. } else {
  480. // Something happened in setting up the request that triggered an Error
  481. console.log('Error', error.message);
  482. }
  483. console.log(error.config);
  484. });
  485. ```
  486. Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
  487. ```js
  488. axios.get('/user/12345', {
  489. validateStatus: function (status) {
  490. return status < 500; // Resolve only if the status code is less than 500
  491. }
  492. })
  493. ```
  494. Using `toJSON` you get an object with more information about the HTTP error.
  495. ```js
  496. axios.get('/user/12345')
  497. .catch(function (error) {
  498. console.log(error.toJSON());
  499. });
  500. ```
  501. ## Cancellation
  502. You can cancel a request using a *cancel token*.
  503. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
  504. You can create a cancel token using the `CancelToken.source` factory as shown below:
  505. ```js
  506. const CancelToken = axios.CancelToken;
  507. const source = CancelToken.source();
  508. axios.get('/user/12345', {
  509. cancelToken: source.token
  510. }).catch(function (thrown) {
  511. if (axios.isCancel(thrown)) {
  512. console.log('Request canceled', thrown.message);
  513. } else {
  514. // handle error
  515. }
  516. });
  517. axios.post('/user/12345', {
  518. name: 'new name'
  519. }, {
  520. cancelToken: source.token
  521. })
  522. // cancel the request (the message parameter is optional)
  523. source.cancel('Operation canceled by the user.');
  524. ```
  525. You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
  526. ```js
  527. const CancelToken = axios.CancelToken;
  528. let cancel;
  529. axios.get('/user/12345', {
  530. cancelToken: new CancelToken(function executor(c) {
  531. // An executor function receives a cancel function as a parameter
  532. cancel = c;
  533. })
  534. });
  535. // cancel the request
  536. cancel();
  537. ```
  538. > Note: you can cancel several requests with the same cancel token.
  539. ## Using application/x-www-form-urlencoded format
  540. By 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.
  541. ### Browser
  542. In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
  543. ```js
  544. const params = new URLSearchParams();
  545. params.append('param1', 'value1');
  546. params.append('param2', 'value2');
  547. axios.post('/foo', params);
  548. ```
  549. > 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).
  550. Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
  551. ```js
  552. const qs = require('qs');
  553. axios.post('/foo', qs.stringify({ 'bar': 123 }));
  554. ```
  555. Or in another way (ES6),
  556. ```js
  557. import qs from 'qs';
  558. const data = { 'bar': 123 };
  559. const options = {
  560. method: 'POST',
  561. headers: { 'content-type': 'application/x-www-form-urlencoded' },
  562. data: qs.stringify(data),
  563. url,
  564. };
  565. axios(options);
  566. ```
  567. ### Node.js
  568. #### Query string
  569. In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
  570. ```js
  571. const querystring = require('querystring');
  572. axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
  573. ```
  574. or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows:
  575. ```js
  576. const url = require('url');
  577. const params = new url.URLSearchParams({ foo: 'bar' });
  578. axios.post('http://something.com/', params.toString());
  579. ```
  580. You can also use the [`qs`](https://github.com/ljharb/qs) library.
  581. ###### NOTE
  582. The `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).
  583. #### Form data
  584. In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
  585. ```js
  586. const FormData = require('form-data');
  587. const form = new FormData();
  588. form.append('my_field', 'my value');
  589. form.append('my_buffer', new Buffer(10));
  590. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
  591. axios.post('https://example.com', form, { headers: form.getHeaders() })
  592. ```
  593. Alternatively, use an interceptor:
  594. ```js
  595. axios.interceptors.request.use(config => {
  596. if (config.data instanceof FormData) {
  597. Object.assign(config.headers, config.data.getHeaders());
  598. }
  599. return config;
  600. });
  601. ```
  602. ## Semver
  603. Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
  604. ## Promises
  605. axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
  606. If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
  607. ## TypeScript
  608. axios includes [TypeScript](http://typescriptlang.org) definitions.
  609. ```typescript
  610. import axios from 'axios';
  611. axios.get('/user?ID=12345');
  612. ```
  613. ## Resources
  614. * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
  615. * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
  616. * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
  617. * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
  618. * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
  619. ## Credits
  620. axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.
  621. ## License
  622. [MIT](LICENSE)