Axios.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. import transitionalDefaults from '../defaults/transitional.js';
  11. const validators = validator.validators;
  12. /**
  13. * Create a new instance of Axios
  14. *
  15. * @param {Object} instanceConfig The default config for the instance
  16. *
  17. * @return {Axios} A new instance of Axios
  18. */
  19. class Axios {
  20. constructor(instanceConfig) {
  21. this.defaults = instanceConfig || {};
  22. this.interceptors = {
  23. request: new InterceptorManager(),
  24. response: new InterceptorManager(),
  25. };
  26. }
  27. /**
  28. * Dispatch a request
  29. *
  30. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  31. * @param {?Object} config
  32. *
  33. * @returns {Promise} The Promise to be fulfilled
  34. */
  35. async request(configOrUrl, config) {
  36. try {
  37. return await this._request(configOrUrl, config);
  38. } catch (err) {
  39. if (err instanceof Error) {
  40. let dummy = {};
  41. Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
  42. // slice off the Error: ... line
  43. const stack = (() => {
  44. if (!dummy.stack) {
  45. return '';
  46. }
  47. const firstNewlineIndex = dummy.stack.indexOf('\n');
  48. return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
  49. })();
  50. try {
  51. if (!err.stack) {
  52. err.stack = stack;
  53. // match without the 2 top stack lines
  54. } else if (stack) {
  55. const firstNewlineIndex = stack.indexOf('\n');
  56. const secondNewlineIndex =
  57. firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
  58. const stackWithoutTwoTopLines =
  59. secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
  60. if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
  61. err.stack += '\n' + stack;
  62. }
  63. }
  64. } catch (e) {
  65. // ignore the case where "stack" is an un-writable property
  66. }
  67. }
  68. throw err;
  69. }
  70. }
  71. _request(configOrUrl, config) {
  72. /*eslint no-param-reassign:0*/
  73. // Allow for axios('example/url'[, config]) a la fetch API
  74. if (typeof configOrUrl === 'string') {
  75. config = config || {};
  76. config.url = configOrUrl;
  77. } else {
  78. config = configOrUrl || {};
  79. }
  80. config = mergeConfig(this.defaults, config);
  81. const { transitional, paramsSerializer, headers } = config;
  82. if (transitional !== undefined) {
  83. validator.assertOptions(
  84. transitional,
  85. {
  86. silentJSONParsing: validators.transitional(validators.boolean),
  87. forcedJSONParsing: validators.transitional(validators.boolean),
  88. clarifyTimeoutError: validators.transitional(validators.boolean),
  89. legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
  90. },
  91. false
  92. );
  93. }
  94. if (paramsSerializer != null) {
  95. if (utils.isFunction(paramsSerializer)) {
  96. config.paramsSerializer = {
  97. serialize: paramsSerializer,
  98. };
  99. } else {
  100. validator.assertOptions(
  101. paramsSerializer,
  102. {
  103. encode: validators.function,
  104. serialize: validators.function,
  105. },
  106. true
  107. );
  108. }
  109. }
  110. // Set config.allowAbsoluteUrls
  111. if (config.allowAbsoluteUrls !== undefined) {
  112. // do nothing
  113. } else if (this.defaults.allowAbsoluteUrls !== undefined) {
  114. config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
  115. } else {
  116. config.allowAbsoluteUrls = true;
  117. }
  118. validator.assertOptions(
  119. config,
  120. {
  121. baseUrl: validators.spelling('baseURL'),
  122. withXsrfToken: validators.spelling('withXSRFToken'),
  123. },
  124. true
  125. );
  126. // Set config.method
  127. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  128. // Flatten headers
  129. let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
  130. headers &&
  131. utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], (method) => {
  132. delete headers[method];
  133. });
  134. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  135. // filter out skipped interceptors
  136. const requestInterceptorChain = [];
  137. let synchronousRequestInterceptors = true;
  138. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  139. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  140. return;
  141. }
  142. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  143. const transitional = config.transitional || transitionalDefaults;
  144. const legacyInterceptorReqResOrdering =
  145. transitional && transitional.legacyInterceptorReqResOrdering;
  146. if (legacyInterceptorReqResOrdering) {
  147. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  148. } else {
  149. requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  150. }
  151. });
  152. const responseInterceptorChain = [];
  153. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  154. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  155. });
  156. let promise;
  157. let i = 0;
  158. let len;
  159. if (!synchronousRequestInterceptors) {
  160. const chain = [dispatchRequest.bind(this), undefined];
  161. chain.unshift(...requestInterceptorChain);
  162. chain.push(...responseInterceptorChain);
  163. len = chain.length;
  164. promise = Promise.resolve(config);
  165. while (i < len) {
  166. promise = promise.then(chain[i++], chain[i++]);
  167. }
  168. return promise;
  169. }
  170. len = requestInterceptorChain.length;
  171. let newConfig = config;
  172. while (i < len) {
  173. const onFulfilled = requestInterceptorChain[i++];
  174. const onRejected = requestInterceptorChain[i++];
  175. try {
  176. newConfig = onFulfilled(newConfig);
  177. } catch (error) {
  178. onRejected.call(this, error);
  179. break;
  180. }
  181. }
  182. try {
  183. promise = dispatchRequest.call(this, newConfig);
  184. } catch (error) {
  185. return Promise.reject(error);
  186. }
  187. i = 0;
  188. len = responseInterceptorChain.length;
  189. while (i < len) {
  190. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  191. }
  192. return promise;
  193. }
  194. getUri(config) {
  195. config = mergeConfig(this.defaults, config);
  196. const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
  197. return buildURL(fullPath, config.params, config.paramsSerializer);
  198. }
  199. }
  200. // Provide aliases for supported request methods
  201. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  202. /*eslint func-names:0*/
  203. Axios.prototype[method] = function (url, config) {
  204. return this.request(
  205. mergeConfig(config || {}, {
  206. method,
  207. url,
  208. data: (config || {}).data,
  209. })
  210. );
  211. };
  212. });
  213. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  214. function generateHTTPMethod(isForm) {
  215. return function httpMethod(url, data, config) {
  216. return this.request(
  217. mergeConfig(config || {}, {
  218. method,
  219. headers: isForm
  220. ? {
  221. 'Content-Type': 'multipart/form-data',
  222. }
  223. : {},
  224. url,
  225. data,
  226. })
  227. );
  228. };
  229. }
  230. Axios.prototype[method] = generateHTTPMethod();
  231. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  232. });
  233. export default Axios;