Axios.js 5.5 KB

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