Axios.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 != null) {
  53. if (utils.isFunction(paramsSerializer)) {
  54. config.paramsSerializer = {
  55. serialize: paramsSerializer
  56. }
  57. } else {
  58. validator.assertOptions(paramsSerializer, {
  59. encode: validators.function,
  60. serialize: validators.function
  61. }, true);
  62. }
  63. }
  64. // Set config.method
  65. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  66. let contextHeaders;
  67. // Flatten headers
  68. contextHeaders = headers && utils.merge(
  69. headers.common,
  70. headers[config.method]
  71. );
  72. contextHeaders && utils.forEach(
  73. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  74. (method) => {
  75. delete headers[method];
  76. }
  77. );
  78. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  79. // filter out skipped interceptors
  80. const requestInterceptorChain = [];
  81. let synchronousRequestInterceptors = true;
  82. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  83. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  84. return;
  85. }
  86. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  87. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  88. });
  89. const responseInterceptorChain = [];
  90. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  91. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  92. });
  93. let promise;
  94. let i = 0;
  95. let len;
  96. if (!synchronousRequestInterceptors) {
  97. const chain = [dispatchRequest.bind(this), undefined];
  98. chain.unshift.apply(chain, requestInterceptorChain);
  99. chain.push.apply(chain, responseInterceptorChain);
  100. len = chain.length;
  101. promise = Promise.resolve(config);
  102. while (i < len) {
  103. promise = promise.then(chain[i++], chain[i++]);
  104. }
  105. return promise;
  106. }
  107. len = requestInterceptorChain.length;
  108. let newConfig = config;
  109. i = 0;
  110. while (i < len) {
  111. const onFulfilled = requestInterceptorChain[i++];
  112. const onRejected = requestInterceptorChain[i++];
  113. try {
  114. newConfig = onFulfilled(newConfig);
  115. } catch (error) {
  116. onRejected.call(this, error);
  117. break;
  118. }
  119. }
  120. try {
  121. promise = dispatchRequest.call(this, newConfig);
  122. } catch (error) {
  123. return Promise.reject(error);
  124. }
  125. i = 0;
  126. len = responseInterceptorChain.length;
  127. while (i < len) {
  128. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  129. }
  130. return promise;
  131. }
  132. getUri(config) {
  133. config = mergeConfig(this.defaults, config);
  134. const fullPath = buildFullPath(config.baseURL, config.url);
  135. return buildURL(fullPath, config.params, config.paramsSerializer);
  136. }
  137. }
  138. // Provide aliases for supported request methods
  139. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  140. /*eslint func-names:0*/
  141. Axios.prototype[method] = function(url, config) {
  142. return this.request(mergeConfig(config || {}, {
  143. method,
  144. url,
  145. data: (config || {}).data
  146. }));
  147. };
  148. });
  149. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  150. /*eslint func-names:0*/
  151. function generateHTTPMethod(isForm) {
  152. return function httpMethod(url, data, config) {
  153. return this.request(mergeConfig(config || {}, {
  154. method,
  155. headers: isForm ? {
  156. 'Content-Type': 'multipart/form-data'
  157. } : {},
  158. url,
  159. data
  160. }));
  161. };
  162. }
  163. Axios.prototype[method] = generateHTTPMethod();
  164. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  165. });
  166. export default Axios;