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