{"_id":"@contentful/axios","_rev":"388461","name":"@contentful/axios","description":"Promise based HTTP client for the browser and node.js","dist-tags":{"latest":"0.18.0"},"maintainers":[{"name":"contentful-ecosystem","email":"support@contentful.com"},{"name":"it-internal","email":""},{"name":"michaelpearce","email":""},{"name":"whydah-gally","email":""}],"time":{"modified":"2021-08-04T03:42:24.000Z","created":"2017-11-16T14:09:50.847Z","0.18.0":"2017-11-16T14:09:50.847Z"},"users":{},"author":{"name":"Matt Zabriskie"},"repository":{"type":"git","url":"git+https://github.com/contentful/axios.git"},"versions":{"0.18.0":{"name":"@contentful/axios","version":"0.18.0","description":"Promise based HTTP client for the browser and node.js","main":"index.js","scripts":{"test":"grunt test && bundlesize","start":"node ./sandbox/server.js","build":"NODE_ENV=production grunt build","preversion":"npm test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json","postversion":"git push && git push --tags","examples":"node ./examples/server.js","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js"},"repository":{"type":"git","url":"git+https://github.com/contentful/axios.git"},"keywords":["xhr","http","ajax","promise","node"],"author":{"name":"Matt Zabriskie"},"license":"MIT","bugs":{"url":"https://github.com/axios/axios/issues"},"homepage":"https://github.com/axios/axios","devDependencies":{"bundlesize":"^0.5.7","coveralls":"^2.11.9","es6-promise":"^4.0.5","grunt":"^1.0.1","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.0.0","grunt-contrib-nodeunit":"^1.0.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^19.0.0","grunt-karma":"^2.0.0","grunt-ts":"^6.0.0-beta.3","grunt-webpack":"^1.0.18","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^1.3.0","karma-chrome-launcher":"^2.0.0","karma-coverage":"^1.0.0","karma-firefox-launcher":"^1.0.0","karma-jasmine":"^1.0.2","karma-jasmine-ajax":"^0.1.13","karma-opera-launcher":"^1.0.0","karma-phantomjs-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^1.1.0","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^1.7.0","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","phantomjs-prebuilt":"^2.1.7","sinon":"^1.17.4","webpack":"^1.13.1","webpack-dev-server":"^1.14.1","url-search-params":"^0.6.1","typescript":"^2.0.3"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"typings":"./index.d.ts","dependencies":{"follow-redirects":"^1.2.5","is-buffer":"^1.1.5"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}],"gitHead":"88b1a1ddf78280316f06785971049d2dab423454","_id":"@contentful/axios@0.18.0","_npmVersion":"5.5.1","_nodeVersion":"8.9.0","_npmUser":{"name":"zcei","email":"stephanschndr@gmail.com"},"dist":{"shasum":"576e0e6047411a66971e82d40688a8c795e62f27","size":80657,"noattachment":false,"key":"/@contentful/axios/-/@contentful/axios-0.18.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/@contentful/axios/download/@contentful/axios-0.18.0.tgz"},"maintainers":[{"name":"contentful-ecosystem","email":"support@contentful.com"},{"name":"it-internal","email":""},{"name":"michaelpearce","email":""},{"name":"whydah-gally","email":""}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/axios-0.18.0.tgz_1510841389438_0.5036548764910549"},"directories":{},"publish_time":1510841390847,"_hasShrinkwrap":false,"_cnpm_publish_time":1510841390847}},"readme":"# axios\n\n[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)\n[![build status](https://img.shields.io/travis/axios/axios.svg?style=flat-square)](https://travis-ci.org/axios/axios)\n[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)\n[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios)\n[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)\n\nPromise based HTTP client for the browser and node.js\n\n## Features\n\n- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser\n- Make [http](http://nodejs.org/api/http.html) requests from node.js\n- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API\n- Intercept request and response\n- Transform request and response data\n- Cancel requests\n- Automatic transforms for JSON data\n- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n\n## Browser Support\n\n![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) |\n--- | --- | --- | --- | --- | --- |\nLatest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |\n\n[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)\n\n## Installing\n\nUsing npm:\n\n```bash\n$ npm install axios\n```\n\nUsing bower:\n\n```bash\n$ bower install axios\n```\n\nUsing cdn:\n\n```html\n<script src=\"https://unpkg.com/axios/dist/axios.min.js\"></script>\n```\n\n## Example\n\nPerforming a `GET` request\n\n```js\n// Make a request for a user with a given ID\naxios.get('/user?ID=12345')\n  .then(function (response) {\n    console.log(response);\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n\n// Optionally the request above could also be done as\naxios.get('/user', {\n    params: {\n      ID: 12345\n    }\n  })\n  .then(function (response) {\n    console.log(response);\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n```\n\nPerforming a `POST` request\n\n```js\naxios.post('/user', {\n    firstName: 'Fred',\n    lastName: 'Flintstone'\n  })\n  .then(function (response) {\n    console.log(response);\n  })\n  .catch(function (error) {\n    console.log(error);\n  });\n```\n\nPerforming multiple concurrent requests\n\n```js\nfunction getUserAccount() {\n  return axios.get('/user/12345');\n}\n\nfunction getUserPermissions() {\n  return axios.get('/user/12345/permissions');\n}\n\naxios.all([getUserAccount(), getUserPermissions()])\n  .then(axios.spread(function (acct, perms) {\n    // Both requests are now complete\n  }));\n```\n\n## axios API\n\nRequests can be made by passing the relevant config to `axios`.\n\n##### axios(config)\n\n```js\n// Send a POST request\naxios({\n  method: 'post',\n  url: '/user/12345',\n  data: {\n    firstName: 'Fred',\n    lastName: 'Flintstone'\n  }\n});\n```\n\n```js\n// GET request for remote image\naxios({\n  method:'get',\n  url:'http://bit.ly/2mTM3nY',\n  responseType:'stream'\n})\n  .then(function(response) {\n  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))\n});\n```\n\n##### axios(url[, config])\n\n```js\n// Send a GET request (default method)\naxios('/user/12345');\n```\n\n### Request method aliases\n\nFor convenience aliases have been provided for all supported request methods.\n\n##### axios.request(config)\n##### axios.get(url[, config])\n##### axios.delete(url[, config])\n##### axios.head(url[, config])\n##### axios.options(url[, config])\n##### axios.post(url[, data[, config]])\n##### axios.put(url[, data[, config]])\n##### axios.patch(url[, data[, config]])\n\n###### NOTE\nWhen using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.\n\n### Concurrency\n\nHelper functions for dealing with concurrent requests.\n\n##### axios.all(iterable)\n##### axios.spread(callback)\n\n### Creating an instance\n\nYou can create a new instance of axios with a custom config.\n\n##### axios.create([config])\n\n```js\nvar instance = axios.create({\n  baseURL: 'https://some-domain.com/api/',\n  timeout: 1000,\n  headers: {'X-Custom-Header': 'foobar'}\n});\n```\n\n### Instance methods\n\nThe available instance methods are listed below. The specified config will be merged with the instance config.\n\n##### axios#request(config)\n##### axios#get(url[, config])\n##### axios#delete(url[, config])\n##### axios#head(url[, config])\n##### axios#options(url[, config])\n##### axios#post(url[, data[, config]])\n##### axios#put(url[, data[, config]])\n##### axios#patch(url[, data[, config]])\n\n## Request Config\n\nThese are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.\n\n```js\n{\n  // `url` is the server URL that will be used for the request\n  url: '/user',\n\n  // `method` is the request method to be used when making the request\n  method: 'get', // default\n\n  // `baseURL` will be prepended to `url` unless `url` is absolute.\n  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs\n  // to methods of that instance.\n  baseURL: 'https://some-domain.com/api/',\n\n  // `transformRequest` allows changes to the request data before it is sent to the server\n  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'\n  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,\n  // FormData or Stream\n  // You may modify the headers object.\n  transformRequest: [function (data, headers) {\n    // Do whatever you want to transform the data\n\n    return data;\n  }],\n\n  // `transformResponse` allows changes to the response data to be made before\n  // it is passed to then/catch\n  transformResponse: [function (data) {\n    // Do whatever you want to transform the data\n\n    return data;\n  }],\n\n  // `headers` are custom headers to be sent\n  headers: {'X-Requested-With': 'XMLHttpRequest'},\n\n  // `params` are the URL parameters to be sent with the request\n  // Must be a plain object or a URLSearchParams object\n  params: {\n    ID: 12345\n  },\n\n  // `paramsSerializer` is an optional function in charge of serializing `params`\n  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)\n  paramsSerializer: function(params) {\n    return Qs.stringify(params, {arrayFormat: 'brackets'})\n  },\n\n  // `data` is the data to be sent as the request body\n  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'\n  // When no `transformRequest` is set, must be of one of the following types:\n  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams\n  // - Browser only: FormData, File, Blob\n  // - Node only: Stream, Buffer\n  data: {\n    firstName: 'Fred'\n  },\n\n  // `timeout` specifies the number of milliseconds before the request times out.\n  // If the request takes longer than `timeout`, the request will be aborted.\n  timeout: 1000,\n\n  // `withCredentials` indicates whether or not cross-site Access-Control requests\n  // should be made using credentials\n  withCredentials: false, // default\n\n  // `adapter` allows custom handling of requests which makes testing easier.\n  // Return a promise and supply a valid response (see lib/adapters/README.md).\n  adapter: function (config) {\n    /* ... */\n  },\n\n  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.\n  // This will set an `Authorization` header, overwriting any existing\n  // `Authorization` custom headers you have set using `headers`.\n  auth: {\n    username: 'janedoe',\n    password: 's00pers3cret'\n  },\n\n  // `responseType` indicates the type of data that the server will respond with\n  // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'\n  responseType: 'json', // default\n\n  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token\n  xsrfCookieName: 'XSRF-TOKEN', // default\n\n  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value\n  xsrfHeaderName: 'X-XSRF-TOKEN', // default\n\n  // `onUploadProgress` allows handling of progress events for uploads\n  onUploadProgress: function (progressEvent) {\n    // Do whatever you want with the native progress event\n  },\n\n  // `onDownloadProgress` allows handling of progress events for downloads\n  onDownloadProgress: function (progressEvent) {\n    // Do whatever you want with the native progress event\n  },\n\n  // `maxContentLength` defines the max size of the http response content allowed\n  maxContentLength: 2000,\n\n  // `validateStatus` defines whether to resolve or reject the promise for a given\n  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`\n  // or `undefined`), the promise will be resolved; otherwise, the promise will be\n  // rejected.\n  validateStatus: function (status) {\n    return status >= 200 && status < 300; // default\n  },\n\n  // `maxRedirects` defines the maximum number of redirects to follow in node.js.\n  // If set to 0, no redirects will be followed.\n  maxRedirects: 5, // default\n\n  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http\n  // and https requests, respectively, in node.js. This allows options to be added like\n  // `keepAlive` that are not enabled by default.\n  httpAgent: new http.Agent({ keepAlive: true }),\n  httpsAgent: new https.Agent({ keepAlive: true }),\n\n  // 'proxy' defines the hostname and port of the proxy server\n  // Use `false` to disable proxies, ignoring environment variables.\n  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and\n  // supplies credentials.\n  // This will set an `Proxy-Authorization` header, overwriting any existing\n  // `Proxy-Authorization` custom headers you have set using `headers`.\n  proxy: {\n    host: '127.0.0.1',\n    port: 9000,\n    auth: {\n      username: 'mikeymike',\n      password: 'rapunz3l'\n    }\n  },\n\n  // `cancelToken` specifies a cancel token that can be used to cancel the request\n  // (see Cancellation section below for details)\n  cancelToken: new CancelToken(function (cancel) {\n  })\n}\n```\n\n## Response Schema\n\nThe response for a request contains the following information.\n\n```js\n{\n  // `data` is the response that was provided by the server\n  data: {},\n\n  // `status` is the HTTP status code from the server response\n  status: 200,\n\n  // `statusText` is the HTTP status message from the server response\n  statusText: 'OK',\n\n  // `headers` the headers that the server responded with\n  // All header names are lower cased\n  headers: {},\n\n  // `config` is the config that was provided to `axios` for the request\n  config: {},\n\n  // `request` is the request that generated this response\n  // It is the last ClientRequest instance in node.js (in redirects)\n  // and an XMLHttpRequest instance the browser\n  request: {}\n}\n```\n\nWhen using `then`, you will receive the response as follows:\n\n```js\naxios.get('/user/12345')\n  .then(function(response) {\n    console.log(response.data);\n    console.log(response.status);\n    console.log(response.statusText);\n    console.log(response.headers);\n    console.log(response.config);\n  });\n```\n\nWhen 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.\n\n## Config Defaults\n\nYou can specify config defaults that will be applied to every request.\n\n### Global axios defaults\n\n```js\naxios.defaults.baseURL = 'https://api.example.com';\naxios.defaults.headers.common['Authorization'] = AUTH_TOKEN;\naxios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';\n```\n\n### Custom instance defaults\n\n```js\n// Set config defaults when creating the instance\nvar instance = axios.create({\n  baseURL: 'https://api.example.com'\n});\n\n// Alter defaults after instance has been created\ninstance.defaults.headers.common['Authorization'] = AUTH_TOKEN;\n```\n\n### Config order of precedence\n\nConfig 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.\n\n```js\n// Create an instance using the config defaults provided by the library\n// At this point the timeout config value is `0` as is the default for the library\nvar instance = axios.create();\n\n// Override timeout default for the library\n// Now all requests will wait 2.5 seconds before timing out\ninstance.defaults.timeout = 2500;\n\n// Override timeout for this request as it's known to take a long time\ninstance.get('/longRequest', {\n  timeout: 5000\n});\n```\n\n## Interceptors\n\nYou can intercept requests or responses before they are handled by `then` or `catch`.\n\n```js\n// Add a request interceptor\naxios.interceptors.request.use(function (config) {\n    // Do something before request is sent\n    return config;\n  }, function (error) {\n    // Do something with request error\n    return Promise.reject(error);\n  });\n\n// Add a response interceptor\naxios.interceptors.response.use(function (response) {\n    // Do something with response data\n    return response;\n  }, function (error) {\n    // Do something with response error\n    return Promise.reject(error);\n  });\n```\n\nIf you may need to remove an interceptor later you can.\n\n```js\nvar myInterceptor = axios.interceptors.request.use(function () {/*...*/});\naxios.interceptors.request.eject(myInterceptor);\n```\n\nYou can add interceptors to a custom instance of axios.\n\n```js\nvar instance = axios.create();\ninstance.interceptors.request.use(function () {/*...*/});\n```\n\n## Handling Errors\n\n```js\naxios.get('/user/12345')\n  .catch(function (error) {\n    if (error.response) {\n      // The request was made and the server responded with a status code\n      // that falls out of the range of 2xx\n      console.log(error.response.data);\n      console.log(error.response.status);\n      console.log(error.response.headers);\n    } else if (error.request) {\n      // The request was made but no response was received\n      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of\n      // http.ClientRequest in node.js\n      console.log(error.request);\n    } else {\n      // Something happened in setting up the request that triggered an Error\n      console.log('Error', error.message);\n    }\n    console.log(error.config);\n  });\n```\n\nYou can define a custom HTTP status code error range using the `validateStatus` config option.\n\n```js\naxios.get('/user/12345', {\n  validateStatus: function (status) {\n    return status < 500; // Reject only if the status code is greater than or equal to 500\n  }\n})\n```\n\n## Cancellation\n\nYou can cancel a request using a *cancel token*.\n\n> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).\n\nYou can create a cancel token using the `CancelToken.source` factory as shown below:\n\n```js\nvar CancelToken = axios.CancelToken;\nvar source = CancelToken.source();\n\naxios.get('/user/12345', {\n  cancelToken: source.token\n}).catch(function(thrown) {\n  if (axios.isCancel(thrown)) {\n    console.log('Request canceled', thrown.message);\n  } else {\n    // handle error\n  }\n});\n\n// cancel the request (the message parameter is optional)\nsource.cancel('Operation canceled by the user.');\n```\n\nYou can also create a cancel token by passing an executor function to the `CancelToken` constructor:\n\n```js\nvar CancelToken = axios.CancelToken;\nvar cancel;\n\naxios.get('/user/12345', {\n  cancelToken: new CancelToken(function executor(c) {\n    // An executor function receives a cancel function as a parameter\n    cancel = c;\n  })\n});\n\n// cancel the request\ncancel();\n```\n\n> Note: you can cancel several requests with the same cancel token.\n\n## Using application/x-www-form-urlencoded format\n\nBy 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.\n\n### Browser\n\nIn a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:\n\n```js\nvar params = new URLSearchParams();\nparams.append('param1', 'value1');\nparams.append('param2', 'value2');\naxios.post('/foo', params);\n```\n\n> 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).\n\nAlternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:\n\n```js\nvar qs = require('qs');\naxios.post('/foo', qs.stringify({ 'bar': 123 }));\n```\n\n### Node.js\n\nIn node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:\n\n```js\nvar querystring = require('querystring');\naxios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));\n```\n\nYou can also use the [`qs`](https://github.com/ljharb/qs) library.\n\n## Semver\n\nUntil 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.\n\n## Promises\n\naxios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).\nIf your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).\n\n## TypeScript\naxios includes [TypeScript](http://typescriptlang.org) definitions.\n```typescript\nimport axios from 'axios';\naxios.get('/user?ID=12345');\n```\n\n## Resources\n\n* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)\n* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)\n* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)\n* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)\n* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)\n\n## Credits\n\naxios 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.\n\n## License\n\nMIT\n","_attachments":{},"homepage":"https://github.com/axios/axios","bugs":{"url":"https://github.com/axios/axios/issues"},"license":"MIT"}