polling-xhr.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /**
  2. * Module requirements.
  3. */
  4. var XMLHttpRequest = require('xmlhttprequest-ssl');
  5. var Polling = require('./polling');
  6. var Emitter = require('component-emitter');
  7. var inherit = require('component-inherit');
  8. var debug = require('debug')('engine.io-client:polling-xhr');
  9. /**
  10. * Module exports.
  11. */
  12. module.exports = XHR;
  13. module.exports.Request = Request;
  14. /**
  15. * Empty function
  16. */
  17. function empty () {}
  18. /**
  19. * XHR Polling constructor.
  20. *
  21. * @param {Object} opts
  22. * @api public
  23. */
  24. function XHR (opts) {
  25. Polling.call(this, opts);
  26. this.requestTimeout = opts.requestTimeout;
  27. this.extraHeaders = opts.extraHeaders;
  28. if (global.location) {
  29. var isSSL = 'https:' === location.protocol;
  30. var port = location.port;
  31. // some user agents have empty `location.port`
  32. if (!port) {
  33. port = isSSL ? 443 : 80;
  34. }
  35. this.xd = opts.hostname !== global.location.hostname ||
  36. port !== opts.port;
  37. this.xs = opts.secure !== isSSL;
  38. }
  39. }
  40. /**
  41. * Inherits from Polling.
  42. */
  43. inherit(XHR, Polling);
  44. /**
  45. * XHR supports binary
  46. */
  47. XHR.prototype.supportsBinary = true;
  48. /**
  49. * Creates a request.
  50. *
  51. * @param {String} method
  52. * @api private
  53. */
  54. XHR.prototype.request = function (opts) {
  55. opts = opts || {};
  56. opts.uri = this.uri();
  57. opts.xd = this.xd;
  58. opts.xs = this.xs;
  59. opts.agent = this.agent || false;
  60. opts.supportsBinary = this.supportsBinary;
  61. opts.enablesXDR = this.enablesXDR;
  62. // SSL options for Node.js client
  63. opts.pfx = this.pfx;
  64. opts.key = this.key;
  65. opts.passphrase = this.passphrase;
  66. opts.cert = this.cert;
  67. opts.ca = this.ca;
  68. opts.ciphers = this.ciphers;
  69. opts.rejectUnauthorized = this.rejectUnauthorized;
  70. opts.requestTimeout = this.requestTimeout;
  71. // other options for Node.js client
  72. opts.extraHeaders = this.extraHeaders;
  73. return new Request(opts);
  74. };
  75. /**
  76. * Sends data.
  77. *
  78. * @param {String} data to send.
  79. * @param {Function} called upon flush.
  80. * @api private
  81. */
  82. XHR.prototype.doWrite = function (data, fn) {
  83. var isBinary = typeof data !== 'string' && data !== undefined;
  84. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  85. var self = this;
  86. req.on('success', fn);
  87. req.on('error', function (err) {
  88. self.onError('xhr post error', err);
  89. });
  90. this.sendXhr = req;
  91. };
  92. /**
  93. * Starts a poll cycle.
  94. *
  95. * @api private
  96. */
  97. XHR.prototype.doPoll = function () {
  98. debug('xhr poll');
  99. var req = this.request();
  100. var self = this;
  101. req.on('data', function (data) {
  102. self.onData(data);
  103. });
  104. req.on('error', function (err) {
  105. self.onError('xhr poll error', err);
  106. });
  107. this.pollXhr = req;
  108. };
  109. /**
  110. * Request constructor
  111. *
  112. * @param {Object} options
  113. * @api public
  114. */
  115. function Request (opts) {
  116. this.method = opts.method || 'GET';
  117. this.uri = opts.uri;
  118. this.xd = !!opts.xd;
  119. this.xs = !!opts.xs;
  120. this.async = false !== opts.async;
  121. this.data = undefined !== opts.data ? opts.data : null;
  122. this.agent = opts.agent;
  123. this.isBinary = opts.isBinary;
  124. this.supportsBinary = opts.supportsBinary;
  125. this.enablesXDR = opts.enablesXDR;
  126. this.requestTimeout = opts.requestTimeout;
  127. // SSL options for Node.js client
  128. this.pfx = opts.pfx;
  129. this.key = opts.key;
  130. this.passphrase = opts.passphrase;
  131. this.cert = opts.cert;
  132. this.ca = opts.ca;
  133. this.ciphers = opts.ciphers;
  134. this.rejectUnauthorized = opts.rejectUnauthorized;
  135. // other options for Node.js client
  136. this.extraHeaders = opts.extraHeaders;
  137. this.create();
  138. }
  139. /**
  140. * Mix in `Emitter`.
  141. */
  142. Emitter(Request.prototype);
  143. /**
  144. * Creates the XHR object and sends the request.
  145. *
  146. * @api private
  147. */
  148. Request.prototype.create = function () {
  149. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  150. // SSL options for Node.js client
  151. opts.pfx = this.pfx;
  152. opts.key = this.key;
  153. opts.passphrase = this.passphrase;
  154. opts.cert = this.cert;
  155. opts.ca = this.ca;
  156. opts.ciphers = this.ciphers;
  157. opts.rejectUnauthorized = this.rejectUnauthorized;
  158. var xhr = this.xhr = new XMLHttpRequest(opts);
  159. var self = this;
  160. try {
  161. debug('xhr open %s: %s', this.method, this.uri);
  162. xhr.open(this.method, this.uri, this.async);
  163. try {
  164. if (this.extraHeaders) {
  165. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  166. for (var i in this.extraHeaders) {
  167. if (this.extraHeaders.hasOwnProperty(i)) {
  168. xhr.setRequestHeader(i, this.extraHeaders[i]);
  169. }
  170. }
  171. }
  172. } catch (e) {}
  173. if ('POST' === this.method) {
  174. try {
  175. if (this.isBinary) {
  176. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  177. } else {
  178. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  179. }
  180. } catch (e) {}
  181. }
  182. try {
  183. xhr.setRequestHeader('Accept', '*/*');
  184. } catch (e) {}
  185. // ie6 check
  186. if ('withCredentials' in xhr) {
  187. xhr.withCredentials = true;
  188. }
  189. if (this.requestTimeout) {
  190. xhr.timeout = this.requestTimeout;
  191. }
  192. if (this.hasXDR()) {
  193. xhr.onload = function () {
  194. self.onLoad();
  195. };
  196. xhr.onerror = function () {
  197. self.onError(xhr.responseText);
  198. };
  199. } else {
  200. xhr.onreadystatechange = function () {
  201. if (xhr.readyState === 2) {
  202. try {
  203. var contentType = xhr.getResponseHeader('Content-Type');
  204. if (self.supportsBinary && contentType === 'application/octet-stream') {
  205. xhr.responseType = 'arraybuffer';
  206. }
  207. } catch (e) {}
  208. }
  209. if (4 !== xhr.readyState) return;
  210. if (200 === xhr.status || 1223 === xhr.status) {
  211. self.onLoad();
  212. } else {
  213. // make sure the `error` event handler that's user-set
  214. // does not throw in the same tick and gets caught here
  215. setTimeout(function () {
  216. self.onError(xhr.status);
  217. }, 0);
  218. }
  219. };
  220. }
  221. debug('xhr data %s', this.data);
  222. xhr.send(this.data);
  223. } catch (e) {
  224. // Need to defer since .create() is called directly fhrom the constructor
  225. // and thus the 'error' event can only be only bound *after* this exception
  226. // occurs. Therefore, also, we cannot throw here at all.
  227. setTimeout(function () {
  228. self.onError(e);
  229. }, 0);
  230. return;
  231. }
  232. if (global.document) {
  233. this.index = Request.requestsCount++;
  234. Request.requests[this.index] = this;
  235. }
  236. };
  237. /**
  238. * Called upon successful response.
  239. *
  240. * @api private
  241. */
  242. Request.prototype.onSuccess = function () {
  243. this.emit('success');
  244. this.cleanup();
  245. };
  246. /**
  247. * Called if we have data.
  248. *
  249. * @api private
  250. */
  251. Request.prototype.onData = function (data) {
  252. this.emit('data', data);
  253. this.onSuccess();
  254. };
  255. /**
  256. * Called upon error.
  257. *
  258. * @api private
  259. */
  260. Request.prototype.onError = function (err) {
  261. this.emit('error', err);
  262. this.cleanup(true);
  263. };
  264. /**
  265. * Cleans up house.
  266. *
  267. * @api private
  268. */
  269. Request.prototype.cleanup = function (fromError) {
  270. if ('undefined' === typeof this.xhr || null === this.xhr) {
  271. return;
  272. }
  273. // xmlhttprequest
  274. if (this.hasXDR()) {
  275. this.xhr.onload = this.xhr.onerror = empty;
  276. } else {
  277. this.xhr.onreadystatechange = empty;
  278. }
  279. if (fromError) {
  280. try {
  281. this.xhr.abort();
  282. } catch (e) {}
  283. }
  284. if (global.document) {
  285. delete Request.requests[this.index];
  286. }
  287. this.xhr = null;
  288. };
  289. /**
  290. * Called upon load.
  291. *
  292. * @api private
  293. */
  294. Request.prototype.onLoad = function () {
  295. var data;
  296. try {
  297. var contentType;
  298. try {
  299. contentType = this.xhr.getResponseHeader('Content-Type');
  300. } catch (e) {}
  301. if (contentType === 'application/octet-stream') {
  302. data = this.xhr.response || this.xhr.responseText;
  303. } else {
  304. data = this.xhr.responseText;
  305. }
  306. } catch (e) {
  307. this.onError(e);
  308. }
  309. if (null != data) {
  310. this.onData(data);
  311. }
  312. };
  313. /**
  314. * Check if it has XDomainRequest.
  315. *
  316. * @api private
  317. */
  318. Request.prototype.hasXDR = function () {
  319. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  320. };
  321. /**
  322. * Aborts the request.
  323. *
  324. * @api public
  325. */
  326. Request.prototype.abort = function () {
  327. this.cleanup();
  328. };
  329. /**
  330. * Aborts pending requests when unloading the window. This is needed to prevent
  331. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  332. * emitted.
  333. */
  334. Request.requestsCount = 0;
  335. Request.requests = {};
  336. if (global.document) {
  337. if (global.attachEvent) {
  338. global.attachEvent('onunload', unloadHandler);
  339. } else if (global.addEventListener) {
  340. global.addEventListener('beforeunload', unloadHandler, false);
  341. }
  342. }
  343. function unloadHandler () {
  344. for (var i in Request.requests) {
  345. if (Request.requests.hasOwnProperty(i)) {
  346. Request.requests[i].abort();
  347. }
  348. }
  349. }