Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

4 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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, port, and protocol 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. // If the proxy server uses HTTPS, then you must set the protocol to `https`.
  349. proxy: {
  350. protocol: 'https',
  351. host: '127.0.0.1',
  352. port: 9000,
  353. auth: {
  354. username: 'mikeymike',
  355. password: 'rapunz3l'
  356. }
  357. },
  358. // `cancelToken` specifies a cancel token that can be used to cancel the request
  359. // (see Cancellation section below for details)
  360. cancelToken: new CancelToken(function (cancel) {
  361. }),
  362. // `decompress` indicates whether or not the response body should be decompressed
  363. // automatically. If set to `true` will also remove the 'content-encoding' header
  364. // from the responses objects of all decompressed responses
  365. // - Node only (XHR cannot turn off decompression)
  366. decompress: true // default
  367. }
  368. ```
  369. ## Response Schema
  370. The response for a request contains the following information.
  371. ```js
  372. {
  373. // `data` is the response that was provided by the server
  374. data: {},
  375. // `status` is the HTTP status code from the server response
  376. status: 200,
  377. // `statusText` is the HTTP status message from the server response
  378. statusText: 'OK',
  379. // `headers` the HTTP headers that the server responded with
  380. // All header names are lower cased and can be accessed using the bracket notation.
  381. // Example: `response.headers['content-type']`
  382. headers: {},
  383. // `config` is the config that was provided to `axios` for the request
  384. config: {},
  385. // `request` is the request that generated this response
  386. // It is the last ClientRequest instance in node.js (in redirects)
  387. // and an XMLHttpRequest instance in the browser
  388. request: {}
  389. }
  390. ```
  391. When using `then`, you will receive the response as follows:
  392. ```js
  393. axios.get('/user/12345')
  394. .then(function (response) {
  395. console.log(response.data);
  396. console.log(response.status);
  397. console.log(response.statusText);
  398. console.log(response.headers);
  399. console.log(response.config);
  400. });
  401. ```
  402. 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.
  403. ## Config Defaults
  404. You can specify config defaults that will be applied to every request.
  405. ### Global axios defaults
  406. ```js
  407. axios.defaults.baseURL = 'https://api.example.com';
  408. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  409. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  410. ```
  411. ### Custom instance defaults
  412. ```js
  413. // Set config defaults when creating the instance
  414. const instance = axios.create({
  415. baseURL: 'https://api.example.com'
  416. });
  417. // Alter defaults after instance has been created
  418. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  419. ```
  420. ### Config order of precedence
  421. 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.
  422. ```js
  423. // Create an instance using the config defaults provided by the library
  424. // At this point the timeout config value is `0` as is the default for the library
  425. const instance = axios.create();
  426. // Override timeout default for the library
  427. // Now all requests using this instance will wait 2.5 seconds before timing out
  428. instance.defaults.timeout = 2500;
  429. // Override timeout for this request as it's known to take a long time
  430. instance.get('/longRequest', {
  431. timeout: 5000
  432. });
  433. ```
  434. ## Interceptors
  435. You can intercept requests or responses before they are handled by `then` or `catch`.
  436. ```js
  437. // Add a request interceptor
  438. axios.interceptors.request.use(function (config) {
  439. // Do something before request is sent
  440. return config;
  441. }, function (error) {
  442. // Do something with request error
  443. return Promise.reject(error);
  444. });
  445. // Add a response interceptor
  446. axios.interceptors.response.use(function (response) {
  447. // Any status code that lie within the range of 2xx cause this function to trigger
  448. // Do something with response data
  449. return response;
  450. }, function (error) {
  451. // Any status codes that falls outside the range of 2xx cause this function to trigger
  452. // Do something with response error
  453. return Promise.reject(error);
  454. });
  455. ```
  456. If you need to remove an interceptor later you can.
  457. ```js
  458. const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
  459. axios.interceptors.request.eject(myInterceptor);
  460. ```
  461. You can add interceptors to a custom instance of axios.
  462. ```js
  463. const instance = axios.create();
  464. instance.interceptors.request.use(function () {/*...*/});
  465. ```
  466. ## Handling Errors
  467. ```js
  468. axios.get('/user/12345')
  469. .catch(function (error) {
  470. if (error.response) {
  471. // The request was made and the server responded with a status code
  472. // that falls out of the range of 2xx
  473. console.log(error.response.data);
  474. console.log(error.response.status);
  475. console.log(error.response.headers);
  476. } else if (error.request) {
  477. // The request was made but no response was received
  478. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  479. // http.ClientRequest in node.js
  480. console.log(error.request);
  481. } else {
  482. // Something happened in setting up the request that triggered an Error
  483. console.log('Error', error.message);
  484. }
  485. console.log(error.config);
  486. });
  487. ```
  488. Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
  489. ```js
  490. axios.get('/user/12345', {
  491. validateStatus: function (status) {
  492. return status < 500; // Resolve only if the status code is less than 500
  493. }
  494. })
  495. ```
  496. Using `toJSON` you get an object with more information about the HTTP error.
  497. ```js
  498. axios.get('/user/12345')
  499. .catch(function (error) {
  500. console.log(error.toJSON());
  501. });
  502. ```
  503. ## Cancellation
  504. You can cancel a request using a *cancel token*.
  505. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
  506. You can create a cancel token using the `CancelToken.source` factory as shown below:
  507. ```js
  508. const CancelToken = axios.CancelToken;
  509. const source = CancelToken.source();
  510. axios.get('/user/12345', {
  511. cancelToken: source.token
  512. }).catch(function (thrown) {
  513. if (axios.isCancel(thrown)) {
  514. console.log('Request canceled', thrown.message);
  515. } else {
  516. // handle error
  517. }
  518. });
  519. axios.post('/user/12345', {
  520. name: 'new name'
  521. }, {
  522. cancelToken: source.token
  523. })
  524. // cancel the request (the message parameter is optional)
  525. source.cancel('Operation canceled by the user.');
  526. ```
  527. You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
  528. ```js
  529. const CancelToken = axios.CancelToken;
  530. let cancel;
  531. axios.get('/user/12345', {
  532. cancelToken: new CancelToken(function executor(c) {
  533. // An executor function receives a cancel function as a parameter
  534. cancel = c;
  535. })
  536. });
  537. // cancel the request
  538. cancel();
  539. ```
  540. > Note: you can cancel several requests with the same cancel token.
  541. ## Using application/x-www-form-urlencoded format
  542. 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.
  543. ### Browser
  544. In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
  545. ```js
  546. const params = new URLSearchParams();
  547. params.append('param1', 'value1');
  548. params.append('param2', 'value2');
  549. axios.post('/foo', params);
  550. ```
  551. > 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).
  552. Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
  553. ```js
  554. const qs = require('qs');
  555. axios.post('/foo', qs.stringify({ 'bar': 123 }));
  556. ```
  557. Or in another way (ES6),
  558. ```js
  559. import qs from 'qs';
  560. const data = { 'bar': 123 };
  561. const options = {
  562. method: 'POST',
  563. headers: { 'content-type': 'application/x-www-form-urlencoded' },
  564. data: qs.stringify(data),
  565. url,
  566. };
  567. axios(options);
  568. ```
  569. ### Node.js
  570. #### Query string
  571. In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
  572. ```js
  573. const querystring = require('querystring');
  574. axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
  575. ```
  576. or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows:
  577. ```js
  578. const url = require('url');
  579. const params = new url.URLSearchParams({ foo: 'bar' });
  580. axios.post('http://something.com/', params.toString());
  581. ```
  582. You can also use the [`qs`](https://github.com/ljharb/qs) library.
  583. ###### NOTE
  584. 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).
  585. #### Form data
  586. In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
  587. ```js
  588. const FormData = require('form-data');
  589. const form = new FormData();
  590. form.append('my_field', 'my value');
  591. form.append('my_buffer', new Buffer(10));
  592. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
  593. axios.post('https://example.com', form, { headers: form.getHeaders() })
  594. ```
  595. Alternatively, use an interceptor:
  596. ```js
  597. axios.interceptors.request.use(config => {
  598. if (config.data instanceof FormData) {
  599. Object.assign(config.headers, config.data.getHeaders());
  600. }
  601. return config;
  602. });
  603. ```
  604. ## Semver
  605. 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.
  606. ## Promises
  607. axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
  608. If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
  609. ## TypeScript
  610. axios includes [TypeScript](http://typescriptlang.org) definitions.
  611. ```typescript
  612. import axios from 'axios';
  613. axios.get('/user?ID=12345');
  614. ```
  615. ## Resources
  616. * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
  617. * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
  618. * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
  619. * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
  620. * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
  621. ## Credits
  622. 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.
  623. ## License
  624. [MIT](LICENSE)