/
xhr.js
77 lines (66 loc) · 2.04 KB
/
xhr.js
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
72
73
74
75
76
77
/**
* Generic Transport for the browser, using the XmlHttpRequest object
*
* @class connections.Xhr
*/
module.exports = XhrConnector;
/* jshint browser:true */
var _ = require('../utils');
var ConnectionAbstract = require('../connection');
var ConnectionFault = require('../errors').ConnectionFault;
var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent));
function XhrConnector(host, config) {
ConnectionAbstract.call(this, host, config);
}
_.inherits(XhrConnector, ConnectionAbstract);
/**
* Simply returns an XHR object cross browser
* @type {Function}
*/
var getXhr = _.noop;
if (typeof XMLHttpRequest !== 'undefined') {
// rewrite the getXhr method to always return the native implementation
getXhr = function () {
return new XMLHttpRequest();
};
} else {
// find the first MS implementation available
getXhr = _.first(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], function (appName) {
/* jshint unused: false */
try {
var test = new window.ActiveXObject(appName);
return function () {
return new window.ActiveXObject(appName);
};
} catch (e) {
return null;
}
});
}
if (!getXhr) {
throw new Error('getXhr(): XMLHttpRequest not available');
}
XhrConnector.prototype.request = function (params, cb) {
var xhr = getXhr();
var timeoutId;
var url = this.host.makeUrl(params);
var log = this.log;
var async = params.async === false ? false : asyncDefault;
if (params.auth) {
xhr.open(params.method || 'GET', url, async, params.auth.user, params.auth.pass);
} else {
xhr.open(params.method || 'GET', url, async);
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
clearTimeout(timeoutId);
log.trace(params.method, url, params.body, xhr.responseText, xhr.status);
var err = xhr.status ? void 0 : new ConnectionFault(xhr.statusText || 'Request failed to complete.');
cb(err, xhr.responseText, xhr.status);
}
};
xhr.send(params.body || void 0);
return function () {
xhr.abort();
};
};