You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.6 KiB

4 years ago
  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. , agent: false
  24. };
  25. var protocol = parsedUrl.protocol === 'https:' ? https : http;
  26. this.req = protocol.request(options, function(res) {
  27. res.setEncoding('utf8');
  28. var responseText = '';
  29. res.on('data', function(chunk) {
  30. debug('data', chunk);
  31. responseText += chunk;
  32. self.emit('chunk', 200, responseText);
  33. });
  34. res.once('end', function() {
  35. debug('end');
  36. self.emit('finish', res.statusCode, responseText);
  37. self.req = null;
  38. });
  39. });
  40. this.req.on('error', function(e) {
  41. debug('error', e);
  42. self.emit('finish', 0, e.message);
  43. });
  44. if (payload) {
  45. this.req.write(payload);
  46. }
  47. this.req.end();
  48. }
  49. inherits(XhrDriver, EventEmitter);
  50. XhrDriver.prototype.close = function() {
  51. debug('close');
  52. this.removeAllListeners();
  53. if (this.req) {
  54. this.req.abort();
  55. this.req = null;
  56. }
  57. };
  58. XhrDriver.enabled = true;
  59. XhrDriver.supportsCORS = true;
  60. module.exports = XhrDriver;