Axios.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. 'use strict';
  2. import utils from './../utils.js';
  3. import buildURL from '../helpers/buildURL.js';
  4. import InterceptorManager from './InterceptorManager.js';
  5. import dispatchRequest from './dispatchRequest.js';
  6. import mergeConfig from './mergeConfig.js';
  7. import buildFullPath from './buildFullPath.js';
  8. import validator from '../helpers/validator.js';
  9. import AxiosHeaders from './AxiosHeaders.js';
  10. const validators = validator.validators;
  11. /**
  12. * Create a new instance of Axios
  13. *
  14. * @param {Object} instanceConfig The default config for the instance
  15. *
  16. * @return {Axios} A new instance of Axios
  17. */
  18. class Axios {
  19. constructor(instanceConfig) {
  20. this.defaults = instanceConfig;
  21. this.interceptors = {
  22. request: new InterceptorManager(),
  23. response: new InterceptorManager()
  24. };
  25. }
  26. /**
  27. * Dispatch a request
  28. *
  29. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  30. * @param {?Object} config
  31. *
  32. * @returns {Promise} The Promise to be fulfilled
  33. */
  34. request(configOrUrl, config) {
  35. /*eslint no-param-reassign:0*/
  36. // Allow for axios('example/url'[, config]) a la fetch API
  37. if (typeof configOrUrl === 'string') {
  38. config = config || {};
  39. config.url = configOrUrl;
  40. } else {
  41. config = configOrUrl || {};
  42. }
  43. config = mergeConfig(this.defaults, config);
  44. const {transitional, paramsSerializer, headers} = config;
  45. if (transitional !== undefined) {
  46. validator.assertOptions(transitional, {
  47. silentJSONParsing: validators.transitional(validators.boolean),
  48. forcedJSONParsing: validators.transitional(validators.boolean),
  49. clarifyTimeoutError: validators.transitional(validators.boolean)
  50. }, false);
  51. }
  52. if (paramsSerializer !== undefined) {
  53. validator.assertOptions(paramsSerializer, {
  54. encode: validators.function,
  55. serialize: validators.function
  56. }, true);
  57. }
  58. // Set config.method
  59. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  60. let contextHeaders;
  61. // Flatten headers
  62. contextHeaders = headers && utils.merge(
  63. headers.common,
  64. headers[config.method]
  65. );
  66. contextHeaders && utils.forEach(
  67. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  68. (method) => {
  69. delete headers[method];
  70. }
  71. );
  72. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  73. // filter out skipped interceptors
  74. const requestInterceptorChain = [];
  75. let synchronousRequestInterceptors = true;
  76. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  77. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  78. return;
  79. }
  80. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  81. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  82. });
  83. const responseInterceptorChain = [];
  84. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  85. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  86. });
  87. let promise;
  88. let i = 0;
  89. let len;
  90. if (!synchronousRequestInterceptors) {
  91. const chain = [dispatchRequest.bind(this), undefined];
  92. chain.unshift.apply(chain, requestInterceptorChain);
  93. chain.push.apply(chain, responseInterceptorChain);
  94. len = chain.length;
  95. promise = Promise.resolve(config);
  96. while (i < len) {
  97. promise = promise.then(chain[i++], chain[i++]);
  98. }
  99. return promise;
  100. }
  101. len = requestInterceptorChain.length;
  102. let newConfig = config;
  103. i = 0;
  104. while (i < len) {
  105. const onFulfilled = requestInterceptorChain[i++];
  106. const onRejected = requestInterceptorChain[i++];
  107. try {
  108. newConfig = onFulfilled(newConfig);
  109. } catch (error) {
  110. onRejected.call(this, error);
  111. break;
  112. }
  113. }
  114. try {
  115. promise = dispatchRequest.call(this, newConfig);
  116. } catch (error) {
  117. return Promise.reject(error);
  118. }
  119. i = 0;
  120. len = responseInterceptorChain.length;
  121. while (i < len) {
  122. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  123. }
  124. return promise;
  125. }
  126. getUri(config) {
  127. config = mergeConfig(this.defaults, config);
  128. const fullPath = buildFullPath(config.baseURL, config.url);
  129. return buildURL(fullPath, config.params, config.paramsSerializer);
  130. }
  131. }
  132. // Provide aliases for supported request methods
  133. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  134. /*eslint func-names:0*/
  135. Axios.prototype[method] = function(url, config) {
  136. return this.request(mergeConfig(config || {}, {
  137. method,
  138. url,
  139. data: (config || {}).data
  140. }));
  141. };
  142. });
  143. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  144. /*eslint func-names:0*/
  145. function generateHTTPMethod(isForm) {
  146. return function httpMethod(url, data, config) {
  147. return this.request(mergeConfig(config || {}, {
  148. method,
  149. headers: isForm ? {
  150. 'Content-Type': 'multipart/form-data'
  151. } : {},
  152. url,
  153. data
  154. }));
  155. };
  156. }
  157. Axios.prototype[method] = generateHTTPMethod();
  158. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  159. });
  160. export default Axios;