xhr.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. 'use strict';
  2. var utils = require('./../utils');
  3. var settle = require('./../core/settle');
  4. var cookies = require('./../helpers/cookies');
  5. var buildURL = require('./../helpers/buildURL');
  6. var buildFullPath = require('../core/buildFullPath');
  7. var parseHeaders = require('./../helpers/parseHeaders');
  8. var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
  9. var createError = require('../core/createError');
  10. var defaults = require('../defaults');
  11. var Cancel = require('../cancel/Cancel');
  12. module.exports = function xhrAdapter(config) {
  13. return new Promise(function dispatchXhrRequest(resolve, reject) {
  14. var requestData = config.data;
  15. var requestHeaders = config.headers;
  16. var responseType = config.responseType;
  17. var onCanceled;
  18. function done() {
  19. if (config.cancelToken) {
  20. config.cancelToken.unsubscribe(onCanceled);
  21. }
  22. if (config.signal) {
  23. config.signal.removeEventListener('abort', onCanceled);
  24. }
  25. }
  26. if (utils.isFormData(requestData)) {
  27. delete requestHeaders['Content-Type']; // Let the browser set it
  28. }
  29. var request = new XMLHttpRequest();
  30. // HTTP basic authentication
  31. if (config.auth) {
  32. var username = config.auth.username || '';
  33. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  34. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  35. }
  36. var fullPath = buildFullPath(config.baseURL, config.url);
  37. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  38. // Set the request timeout in MS
  39. request.timeout = config.timeout;
  40. function onloadend() {
  41. if (!request) {
  42. return;
  43. }
  44. // Prepare the response
  45. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  46. var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
  47. request.responseText : request.response;
  48. var response = {
  49. data: responseData,
  50. status: request.status,
  51. statusText: request.statusText,
  52. headers: responseHeaders,
  53. config: config,
  54. request: request
  55. };
  56. settle(function _resolve(value) {
  57. resolve(value);
  58. done();
  59. }, function _reject(err) {
  60. reject(err);
  61. done();
  62. }, response);
  63. // Clean up request
  64. request = null;
  65. }
  66. if ('onloadend' in request) {
  67. // Use onloadend if available
  68. request.onloadend = onloadend;
  69. } else {
  70. // Listen for ready state to emulate onloadend
  71. request.onreadystatechange = function handleLoad() {
  72. if (!request || request.readyState !== 4) {
  73. return;
  74. }
  75. // The request errored out and we didn't get a response, this will be
  76. // handled by onerror instead
  77. // With one exception: request that using file: protocol, most browsers
  78. // will return status as 0 even though it's a successful request
  79. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  80. return;
  81. }
  82. // readystate handler is calling before onerror or ontimeout handlers,
  83. // so we should call onloadend on the next 'tick'
  84. setTimeout(onloadend);
  85. };
  86. }
  87. // Handle browser request cancellation (as opposed to a manual cancellation)
  88. request.onabort = function handleAbort() {
  89. if (!request) {
  90. return;
  91. }
  92. reject(createError('Request aborted', config, 'ECONNABORTED', request));
  93. // Clean up request
  94. request = null;
  95. };
  96. // Handle low level network errors
  97. request.onerror = function handleError() {
  98. // Real errors are hidden from us by the browser
  99. // onerror should only fire if it's a network error
  100. reject(createError('Network Error', config, null, request));
  101. // Clean up request
  102. request = null;
  103. };
  104. // Handle timeout
  105. request.ontimeout = function handleTimeout() {
  106. var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
  107. var transitional = config.transitional || defaults.transitional;
  108. if (config.timeoutErrorMessage) {
  109. timeoutErrorMessage = config.timeoutErrorMessage;
  110. }
  111. reject(createError(
  112. timeoutErrorMessage,
  113. config,
  114. transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
  115. request));
  116. // Clean up request
  117. request = null;
  118. };
  119. // Add xsrf header
  120. // This is only done if running in a standard browser environment.
  121. // Specifically not if we're in a web worker, or react-native.
  122. if (utils.isStandardBrowserEnv()) {
  123. // Add xsrf header
  124. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  125. cookies.read(config.xsrfCookieName) :
  126. undefined;
  127. if (xsrfValue) {
  128. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  129. }
  130. }
  131. // Add headers to the request
  132. if ('setRequestHeader' in request) {
  133. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  134. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  135. // Remove Content-Type if data is undefined
  136. delete requestHeaders[key];
  137. } else {
  138. // Otherwise add header to the request
  139. request.setRequestHeader(key, val);
  140. }
  141. });
  142. }
  143. // Add withCredentials to request if needed
  144. if (!utils.isUndefined(config.withCredentials)) {
  145. request.withCredentials = !!config.withCredentials;
  146. }
  147. // Add responseType to request if needed
  148. if (responseType && responseType !== 'json') {
  149. request.responseType = config.responseType;
  150. }
  151. // Handle progress if needed
  152. if (typeof config.onDownloadProgress === 'function') {
  153. request.addEventListener('progress', config.onDownloadProgress);
  154. }
  155. // Not all browsers support upload events
  156. if (typeof config.onUploadProgress === 'function' && request.upload) {
  157. request.upload.addEventListener('progress', config.onUploadProgress);
  158. }
  159. if (config.cancelToken || config.signal) {
  160. // Handle cancellation
  161. // eslint-disable-next-line func-names
  162. onCanceled = function(cancel) {
  163. if (!request) {
  164. return;
  165. }
  166. reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);
  167. request.abort();
  168. request = null;
  169. };
  170. config.cancelToken && config.cancelToken.subscribe(onCanceled);
  171. if (config.signal) {
  172. config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
  173. }
  174. }
  175. if (!requestData) {
  176. requestData = null;
  177. }
  178. // Send the request
  179. request.send(requestData);
  180. });
  181. };