Axios.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. async request(configOrUrl, config) {
  35. try {
  36. return await this._request(configOrUrl, config);
  37. } catch (err) {
  38. if (err instanceof Error) {
  39. let dummy;
  40. Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
  41. // slice off the Error: ... line
  42. const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
  43. if (!err.stack) {
  44. err.stack = stack;
  45. // match without the 2 top stack lines
  46. } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
  47. err.stack += '\n' + stack
  48. }
  49. }
  50. throw err;
  51. }
  52. }
  53. _request(configOrUrl, config) {
  54. /*eslint no-param-reassign:0*/
  55. // Allow for axios('example/url'[, config]) a la fetch API
  56. if (typeof configOrUrl === 'string') {
  57. config = config || {};
  58. config.url = configOrUrl;
  59. } else {
  60. config = configOrUrl || {};
  61. }
  62. config = mergeConfig(this.defaults, config);
  63. const {transitional, paramsSerializer, headers} = config;
  64. if (transitional !== undefined) {
  65. validator.assertOptions(transitional, {
  66. silentJSONParsing: validators.transitional(validators.boolean),
  67. forcedJSONParsing: validators.transitional(validators.boolean),
  68. clarifyTimeoutError: validators.transitional(validators.boolean)
  69. }, false);
  70. }
  71. if (paramsSerializer != null) {
  72. if (utils.isFunction(paramsSerializer)) {
  73. config.paramsSerializer = {
  74. serialize: paramsSerializer
  75. }
  76. } else {
  77. validator.assertOptions(paramsSerializer, {
  78. encode: validators.function,
  79. serialize: validators.function
  80. }, true);
  81. }
  82. }
  83. // Set config.method
  84. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  85. // Flatten headers
  86. let contextHeaders = headers && utils.merge(
  87. headers.common,
  88. headers[config.method]
  89. );
  90. headers && utils.forEach(
  91. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  92. (method) => {
  93. delete headers[method];
  94. }
  95. );
  96. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  97. // filter out skipped interceptors
  98. const requestInterceptorChain = [];
  99. let synchronousRequestInterceptors = true;
  100. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  101. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  102. return;
  103. }
  104. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  105. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  106. });
  107. const responseInterceptorChain = [];
  108. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  109. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  110. });
  111. let promise;
  112. let i = 0;
  113. let len;
  114. if (!synchronousRequestInterceptors) {
  115. const chain = [dispatchRequest.bind(this), undefined];
  116. chain.unshift.apply(chain, requestInterceptorChain);
  117. chain.push.apply(chain, responseInterceptorChain);
  118. len = chain.length;
  119. promise = Promise.resolve(config);
  120. while (i < len) {
  121. promise = promise.then(chain[i++], chain[i++]);
  122. }
  123. return promise;
  124. }
  125. len = requestInterceptorChain.length;
  126. let newConfig = config;
  127. i = 0;
  128. while (i < len) {
  129. const onFulfilled = requestInterceptorChain[i++];
  130. const onRejected = requestInterceptorChain[i++];
  131. try {
  132. newConfig = onFulfilled(newConfig);
  133. } catch (error) {
  134. onRejected.call(this, error);
  135. break;
  136. }
  137. }
  138. try {
  139. promise = dispatchRequest.call(this, newConfig);
  140. } catch (error) {
  141. return Promise.reject(error);
  142. }
  143. i = 0;
  144. len = responseInterceptorChain.length;
  145. while (i < len) {
  146. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  147. }
  148. return promise;
  149. }
  150. getUri(config) {
  151. config = mergeConfig(this.defaults, config);
  152. const fullPath = buildFullPath(config.baseURL, config.url);
  153. return buildURL(fullPath, config.params, config.paramsSerializer);
  154. }
  155. }
  156. // Provide aliases for supported request methods
  157. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  158. /*eslint func-names:0*/
  159. Axios.prototype[method] = function(url, config) {
  160. return this.request(mergeConfig(config || {}, {
  161. method,
  162. url,
  163. data: (config || {}).data
  164. }));
  165. };
  166. });
  167. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  168. /*eslint func-names:0*/
  169. function generateHTTPMethod(isForm) {
  170. return function httpMethod(url, data, config) {
  171. return this.request(mergeConfig(config || {}, {
  172. method,
  173. headers: isForm ? {
  174. 'Content-Type': 'multipart/form-data'
  175. } : {},
  176. url,
  177. data
  178. }));
  179. };
  180. }
  181. Axios.prototype[method] = generateHTTPMethod();
  182. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  183. });
  184. export default Axios;