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