xhr.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import utils from '../utils.js';
  2. import settle from '../core/settle.js';
  3. import transitionalDefaults from '../defaults/transitional.js';
  4. import AxiosError from '../core/AxiosError.js';
  5. import CanceledError from '../cancel/CanceledError.js';
  6. import normalizeURLForProtocolCheck from '../helpers/normalizeURLForProtocolCheck.js';
  7. import parseProtocol from '../helpers/parseProtocol.js';
  8. import platform from '../platform/index.js';
  9. import AxiosHeaders from '../core/AxiosHeaders.js';
  10. import cookies from '../helpers/cookies.js';
  11. import { progressEventReducer } from '../helpers/progressEventReducer.js';
  12. import resolveConfig from '../helpers/resolveConfig.js';
  13. import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
  14. const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
  15. export default isXHRAdapterSupported &&
  16. function (config) {
  17. return new Promise(function dispatchXhrRequest(resolve, reject) {
  18. let useAsyncXsrf;
  19. try {
  20. const store =
  21. platform.hasStandardBrowserEnv && typeof window !== 'undefined' && window.cookieStore;
  22. useAsyncXsrf = store && utils.isFunction(store.get);
  23. } catch (e) {
  24. // A restricted Cookie Store getter must retain the synchronous fallback.
  25. }
  26. let xsrfCookieName;
  27. const _config = resolveConfig(
  28. config,
  29. useAsyncXsrf
  30. ? (name) => {
  31. xsrfCookieName = name;
  32. return null;
  33. }
  34. : undefined
  35. );
  36. let requestData = _config.data;
  37. const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
  38. let { responseType, onUploadProgress, onDownloadProgress } = _config;
  39. let onCanceled;
  40. let timeoutId;
  41. let uploadThrottled, downloadThrottled;
  42. let flushUpload, flushDownload, flushDownloadWithEvent;
  43. function done() {
  44. clearTimeout(timeoutId);
  45. // A final progress callback must not prevent the remaining cleanup.
  46. // Report errors asynchronously, as onloadend and the throttle timer do.
  47. try {
  48. flushUpload && flushUpload(); // flush events
  49. } catch (err) {
  50. setTimeout(() => {
  51. throw err;
  52. });
  53. }
  54. try {
  55. flushDownload && flushDownload(); // flush events
  56. } catch (err) {
  57. setTimeout(() => {
  58. throw err;
  59. });
  60. }
  61. // A flush can synchronously cancel the request and reenter done().
  62. // In that case the inner call has already detached these listeners.
  63. if (request) {
  64. downloadThrottled && request.removeEventListener('progress', downloadThrottled);
  65. if (request.upload) {
  66. uploadThrottled && request.upload.removeEventListener('progress', uploadThrottled);
  67. flushUpload && request.upload.removeEventListener('loadend', flushUpload);
  68. }
  69. }
  70. _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
  71. _config.signal && _config.signal.removeEventListener('abort', onCanceled);
  72. }
  73. let request = new XMLHttpRequest();
  74. request.open(_config.method.toUpperCase(), _config.url, true);
  75. // Set the request timeout in MS
  76. request.timeout = _config.timeout;
  77. function onloadend(event) {
  78. if (!request) {
  79. return;
  80. }
  81. // Status 0 means no response was received, which onerror and onabort normally
  82. // reject before this runs. Firefox 152 fires only readystatechange and loadend for
  83. // navigation-canceled requests (https://bugzilla.mozilla.org/show_bug.cgi?id=1505389),
  84. // leaving settle() to resolve them as an empty success. ECONNABORTED is the error
  85. // onabort raised on Firefox 151. Reads over file:, which some environments report as
  86. // status 0 on success, are excluded by the request URL's scheme after browser-style
  87. // preprocessing, by the page origin's scheme for relative URLs (which inherit it), or
  88. // by responseURL where implemented.
  89. if (
  90. request.status === 0 &&
  91. (parseProtocol(normalizeURLForProtocolCheck(_config.url)) ||
  92. parseProtocol(platform.origin)) !== 'file' &&
  93. !(request.responseURL && request.responseURL.startsWith('file:'))
  94. ) {
  95. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  96. done();
  97. // Clean up request
  98. request = null;
  99. return;
  100. }
  101. // When loadend is still dispatching, flushing with it gives progress
  102. // listeners a final delivery whose event has a live target. The legacy
  103. // ready-state fallback has no event, so replay its pending progress.
  104. // A throwing listener must not block settlement; rethrow asynchronously,
  105. // matching how listener errors surface on the throttle timer path.
  106. try {
  107. if (event) {
  108. flushDownloadWithEvent && flushDownloadWithEvent(event);
  109. } else {
  110. flushDownload && flushDownload();
  111. }
  112. } catch (err) {
  113. setTimeout(() => {
  114. throw err;
  115. });
  116. }
  117. // A final progress callback can cancel the request synchronously.
  118. if (!request) {
  119. return;
  120. }
  121. // Prepare the response
  122. const responseHeaders = AxiosHeaders.from(
  123. 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
  124. );
  125. const responseData =
  126. !responseType || responseType === 'text' || responseType === 'json'
  127. ? request.responseText
  128. : request.response;
  129. const response = {
  130. data: responseData,
  131. status: request.status,
  132. statusText: request.statusText,
  133. headers: responseHeaders,
  134. config,
  135. request,
  136. };
  137. settle(
  138. function _resolve(value) {
  139. resolve(value);
  140. done();
  141. },
  142. function _reject(err) {
  143. reject(err);
  144. done();
  145. },
  146. response
  147. );
  148. // Clean up request
  149. request = null;
  150. }
  151. if ('onloadend' in request) {
  152. // Use onloadend if available
  153. request.onloadend = onloadend;
  154. } else {
  155. // Listen for ready state to emulate onloadend
  156. request.onreadystatechange = function handleLoad() {
  157. if (!request || request.readyState !== 4) {
  158. return;
  159. }
  160. // The request errored out and we didn't get a response, this will be
  161. // handled by onerror instead
  162. // With one exception: request that using file: protocol, most browsers
  163. // will return status as 0 even though it's a successful request
  164. if (
  165. request.status === 0 &&
  166. !(request.responseURL && request.responseURL.startsWith('file:'))
  167. ) {
  168. return;
  169. }
  170. // readystate handler is calling before onerror or ontimeout handlers,
  171. // so we should call onloadend on the next 'tick'
  172. setTimeout(onloadend);
  173. };
  174. }
  175. // Handle browser request cancellation (as opposed to a manual cancellation)
  176. request.onabort = function handleAbort() {
  177. if (!request) {
  178. return;
  179. }
  180. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  181. done();
  182. // Clean up request
  183. request = null;
  184. };
  185. // Handle low level network errors
  186. request.onerror = function handleError(event) {
  187. // Browsers deliver a ProgressEvent in XHR onerror
  188. // (message may be empty; when present, surface it)
  189. // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
  190. const msg = event && event.message ? event.message : 'Network Error';
  191. const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
  192. // attach the underlying event for consumers who want details
  193. err.event = event || null;
  194. reject(err);
  195. done();
  196. request = null;
  197. };
  198. // Handle timeout
  199. request.ontimeout = function handleTimeout() {
  200. if (!request) return;
  201. let timeoutErrorMessage = _config.timeout
  202. ? 'timeout of ' + _config.timeout + 'ms exceeded'
  203. : 'timeout exceeded';
  204. const transitional = _config.transitional || transitionalDefaults;
  205. if (_config.timeoutErrorMessage) {
  206. timeoutErrorMessage = _config.timeoutErrorMessage;
  207. }
  208. reject(
  209. new AxiosError(
  210. timeoutErrorMessage,
  211. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  212. config,
  213. request
  214. )
  215. );
  216. done();
  217. // Clean up request
  218. request = null;
  219. };
  220. // Remove Content-Type if data is undefined
  221. requestData === undefined && requestHeaders.setContentType(null);
  222. // Add withCredentials to request if needed
  223. if (!utils.isUndefined(_config.withCredentials)) {
  224. request.withCredentials = !!_config.withCredentials;
  225. }
  226. // Add responseType to request if needed
  227. if (responseType && responseType !== 'json') {
  228. request.responseType = _config.responseType;
  229. }
  230. // Handle progress if needed
  231. if (onDownloadProgress) {
  232. [downloadThrottled, flushDownload, flushDownloadWithEvent] = progressEventReducer(
  233. onDownloadProgress,
  234. true
  235. );
  236. request.addEventListener('progress', downloadThrottled);
  237. }
  238. // Not all browsers support upload events
  239. if (onUploadProgress && request.upload) {
  240. [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
  241. request.upload.addEventListener('progress', uploadThrottled);
  242. request.upload.addEventListener('loadend', flushUpload);
  243. }
  244. if (_config.cancelToken || _config.signal) {
  245. // Handle cancellation
  246. // eslint-disable-next-line func-names
  247. onCanceled = (cancel) => {
  248. if (!request) {
  249. return;
  250. }
  251. reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
  252. const xhr = request;
  253. done();
  254. request = null;
  255. xhr.abort();
  256. };
  257. _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
  258. if (!request) return;
  259. if (_config.signal) {
  260. _config.signal.aborted
  261. ? onCanceled()
  262. : _config.signal.addEventListener('abort', onCanceled);
  263. }
  264. }
  265. if (!request) return;
  266. const protocol = parseProtocol(_config.url);
  267. if (protocol && !platform.protocols.includes(protocol)) {
  268. reject(
  269. new AxiosError(
  270. 'Unsupported protocol ' + protocol + ':',
  271. AxiosError.ERR_BAD_REQUEST,
  272. config
  273. )
  274. );
  275. done();
  276. return;
  277. }
  278. const sendRequest = () => {
  279. if (!request) return;
  280. // Apply headers after an asynchronous XSRF read so existing headers are
  281. // replaced through AxiosHeaders rather than appended by the native XHR.
  282. if ('setRequestHeader' in request) {
  283. utils.forEach(
  284. toByteStringHeaderObject(requestHeaders),
  285. function setRequestHeader(val, key) {
  286. request.setRequestHeader(key, val);
  287. }
  288. );
  289. }
  290. request.send(requestData || null);
  291. };
  292. if (xsrfCookieName) {
  293. // Native XHR timeout starts at send(). Cover cookie preparation and the
  294. // subsequent request with the same budget and existing timeout handler.
  295. const now =
  296. typeof performance !== 'undefined' && utils.isFunction(performance.now)
  297. ? () => performance.now()
  298. : Date.now;
  299. const deadline = request.timeout > 0 ? now() + Number(request.timeout) : undefined;
  300. const abortOnTimeout = () => {
  301. if (!request) return;
  302. const xhr = request;
  303. xhr.ontimeout();
  304. xhr.abort();
  305. };
  306. if (deadline !== undefined) {
  307. const scheduleTimeout = () => {
  308. const remaining = deadline - now();
  309. if (remaining > 0) {
  310. // Browser timers overflow above the signed 32-bit delay limit.
  311. timeoutId = setTimeout(scheduleTimeout, Math.min(remaining, 0x7fffffff));
  312. } else {
  313. abortOnTimeout();
  314. }
  315. };
  316. scheduleTimeout();
  317. }
  318. cookies
  319. .readAsync(xsrfCookieName)
  320. .then((value) => {
  321. if (!request) return;
  322. // Promise callbacks may run before an overdue timer after a busy task.
  323. if (deadline !== undefined && now() >= deadline) {
  324. abortOnTimeout();
  325. return;
  326. }
  327. if (value) {
  328. const headerName =
  329. utils.hasOwnProp(_config, 'xsrfHeaderName') && _config.xsrfHeaderName;
  330. requestHeaders.set(headerName, value);
  331. }
  332. sendRequest();
  333. })
  334. .catch((error) => {
  335. if (!request) return;
  336. reject(AxiosError.from(error, null, config, request));
  337. done();
  338. request = null;
  339. });
  340. } else {
  341. sendRequest();
  342. }
  343. });
  344. };