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