UNPKG

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