defaults.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. var utils = require('./utils');
  3. var normalizeHeaderName = require('./helpers/normalizeHeaderName');
  4. var DEFAULT_CONTENT_TYPE = {
  5. 'Content-Type': 'application/x-www-form-urlencoded'
  6. };
  7. function setContentTypeIfUnset(headers, value) {
  8. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  9. headers['Content-Type'] = value;
  10. }
  11. }
  12. function getDefaultAdapter() {
  13. var adapter;
  14. if (typeof XMLHttpRequest !== 'undefined') {
  15. // For browsers use XHR adapter
  16. adapter = require('./adapters/xhr');
  17. } else if (typeof process !== 'undefined') {
  18. // For node use HTTP adapter
  19. adapter = require('./adapters/http');
  20. }
  21. return adapter;
  22. }
  23. var defaults = {
  24. adapter: getDefaultAdapter(),
  25. transformRequest: [function transformRequest(data, headers) {
  26. normalizeHeaderName(headers, 'Content-Type');
  27. if (utils.isFormData(data) ||
  28. utils.isArrayBuffer(data) ||
  29. utils.isBuffer(data) ||
  30. utils.isStream(data) ||
  31. utils.isFile(data) ||
  32. utils.isBlob(data)
  33. ) {
  34. return data;
  35. }
  36. if (utils.isArrayBufferView(data)) {
  37. return data.buffer;
  38. }
  39. if (utils.isURLSearchParams(data)) {
  40. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  41. return data.toString();
  42. }
  43. if (utils.isObject(data)) {
  44. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  45. return JSON.stringify(data);
  46. }
  47. return data;
  48. }],
  49. transformResponse: [function transformResponse(data) {
  50. /*eslint no-param-reassign:0*/
  51. if (typeof data === 'string') {
  52. try {
  53. data = JSON.parse(data);
  54. } catch (e) { /* Ignore */ }
  55. }
  56. return data;
  57. }],
  58. timeout: 0,
  59. xsrfCookieName: 'XSRF-TOKEN',
  60. xsrfHeaderName: 'X-XSRF-TOKEN',
  61. maxContentLength: -1,
  62. validateStatus: function validateStatus(status) {
  63. return status >= 200 && status < 300;
  64. }
  65. };
  66. defaults.headers = {
  67. common: {
  68. 'Accept': 'application/json, text/plain, */*'
  69. }
  70. };
  71. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  72. defaults.headers[method] = {};
  73. });
  74. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  75. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  76. });
  77. module.exports = defaults;