UNPKG

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