Axios.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
  91. validateStatusUndefinedResolves: validators.transitional(validators.boolean),
  92. },
  93. false
  94. );
  95. }
  96. if (paramsSerializer != null) {
  97. if (utils.isFunction(paramsSerializer)) {
  98. config.paramsSerializer = {
  99. serialize: paramsSerializer,
  100. };
  101. } else {
  102. validator.assertOptions(
  103. paramsSerializer,
  104. {
  105. encode: validators.function,
  106. serialize: validators.function,
  107. },
  108. true
  109. );
  110. }
  111. }
  112. // Set config.allowAbsoluteUrls
  113. if (config.allowAbsoluteUrls !== undefined) {
  114. // do nothing
  115. } else if (this.defaults.allowAbsoluteUrls !== undefined) {
  116. config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
  117. } else {
  118. config.allowAbsoluteUrls = true;
  119. }
  120. validator.assertOptions(
  121. config,
  122. {
  123. baseUrl: validators.spelling('baseURL'),
  124. withXsrfToken: validators.spelling('withXSRFToken'),
  125. },
  126. true
  127. );
  128. // Set config.method
  129. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  130. // Flatten headers
  131. let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
  132. headers &&
  133. utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => {
  134. delete headers[method];
  135. });
  136. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  137. // filter out skipped interceptors
  138. const requestInterceptorChain = [];
  139. let synchronousRequestInterceptors = true;
  140. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  141. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  142. return;
  143. }
  144. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  145. const transitional = config.transitional || transitionalDefaults;
  146. const legacyInterceptorReqResOrdering =
  147. transitional && transitional.legacyInterceptorReqResOrdering;
  148. if (legacyInterceptorReqResOrdering) {
  149. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  150. } else {
  151. requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  152. }
  153. });
  154. const responseInterceptorChain = [];
  155. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  156. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  157. });
  158. let promise;
  159. let i = 0;
  160. let len;
  161. if (!synchronousRequestInterceptors) {
  162. const chain = [dispatchRequest.bind(this), undefined];
  163. chain.unshift(...requestInterceptorChain);
  164. chain.push(...responseInterceptorChain);
  165. len = chain.length;
  166. promise = Promise.resolve(config);
  167. while (i < len) {
  168. promise = promise.then(chain[i++], chain[i++]);
  169. }
  170. return promise;
  171. }
  172. len = requestInterceptorChain.length;
  173. let newConfig = config;
  174. while (i < len) {
  175. const onFulfilled = requestInterceptorChain[i++];
  176. const onRejected = requestInterceptorChain[i++];
  177. try {
  178. newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig;
  179. } catch (error) {
  180. if (!onRejected) {
  181. promise = Promise.reject(error);
  182. break;
  183. }
  184. try {
  185. const rejectedResult = onRejected.call(this, error);
  186. if (utils.isThenable(rejectedResult)) {
  187. promise = Promise.resolve(rejectedResult).then(() =>
  188. dispatchRequest.call(this, newConfig)
  189. );
  190. }
  191. } catch (rejectedError) {
  192. promise = Promise.reject(rejectedError);
  193. }
  194. break;
  195. }
  196. }
  197. if (!promise) {
  198. try {
  199. promise = dispatchRequest.call(this, newConfig);
  200. } catch (error) {
  201. promise = Promise.reject(error);
  202. }
  203. }
  204. i = 0;
  205. len = responseInterceptorChain.length;
  206. while (i < len) {
  207. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  208. }
  209. return promise;
  210. }
  211. getUri(config) {
  212. config = mergeConfig(this.defaults, config);
  213. const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
  214. return buildURL(fullPath, config.params, config.paramsSerializer);
  215. }
  216. }
  217. // Provide aliases for supported request methods
  218. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  219. /*eslint func-names:0*/
  220. Axios.prototype[method] = function (url, config) {
  221. return this.request(
  222. mergeConfig(config || {}, {
  223. method,
  224. url,
  225. data: config && utils.hasOwnProp(config, 'data') ? config.data : undefined,
  226. })
  227. );
  228. };
  229. });
  230. utils.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
  231. function generateHTTPMethod(isForm) {
  232. return function httpMethod(url, data, config) {
  233. return this.request(
  234. mergeConfig(config || {}, {
  235. method,
  236. headers: isForm
  237. ? {
  238. 'Content-Type': 'multipart/form-data',
  239. }
  240. : {},
  241. url,
  242. data,
  243. })
  244. );
  245. };
  246. }
  247. Axios.prototype[method] = generateHTTPMethod();
  248. // QUERY is a safe/idempotent read method; multipart form bodies don't fit
  249. // its semantics, so no queryForm shorthand is generated.
  250. if (method !== 'query') {
  251. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  252. }
  253. });
  254. export default Axios;