xhr.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('inherits')
  4. , http = require('http')
  5. , https = require('https')
  6. , URL = require('url-parse')
  7. ;
  8. var debug = function() {};
  9. if (process.env.NODE_ENV !== 'production') {
  10. debug = require('debug')('sockjs-client:driver:xhr');
  11. }
  12. function XhrDriver(method, url, payload, opts) {
  13. debug(method, url, payload);
  14. var self = this;
  15. EventEmitter.call(this);
  16. var parsedUrl = new URL(url);
  17. var options = {
  18. method: method
  19. , hostname: parsedUrl.hostname.replace(/\[|\]/g, '')
  20. , port: parsedUrl.port
  21. , path: parsedUrl.pathname + (parsedUrl.query || '')
  22. , headers: opts && opts.headers
  23. };
  24. var protocol = parsedUrl.protocol === 'https:' ? https : http;
  25. this.req = protocol.request(options, function(res) {
  26. res.setEncoding('utf8');
  27. var responseText = '';
  28. res.on('data', function(chunk) {
  29. debug('data', chunk);
  30. responseText += chunk;
  31. self.emit('chunk', 200, responseText);
  32. });
  33. res.once('end', function() {
  34. debug('end');
  35. self.emit('finish', res.statusCode, responseText);
  36. self.req = null;
  37. });
  38. });
  39. this.req.on('error', function(e) {
  40. debug('error', e);
  41. self.emit('finish', 0, e.message);
  42. });
  43. if (payload) {
  44. this.req.write(payload);
  45. }
  46. this.req.end();
  47. }
  48. inherits(XhrDriver, EventEmitter);
  49. XhrDriver.prototype.close = function() {
  50. debug('close');
  51. this.removeAllListeners();
  52. if (this.req) {
  53. this.req.abort();
  54. this.req = null;
  55. }
  56. };
  57. XhrDriver.enabled = true;
  58. XhrDriver.supportsCORS = true;
  59. module.exports = XhrDriver;