Axios.js 6.4 KB

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