Skip to content

Commit 4e51485

Browse files
committed
node.js support, via npm package 'xmlhttprequest'
Fixes #29
1 parent ce70237 commit 4e51485

File tree

1 file changed

+42
-4
lines changed

1 file changed

+42
-4
lines changed

src/Network/HTTP/Affjax.js

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,52 @@
1-
/* jshint browser: true */
21
/* global exports */
2+
/* global XMLHttpRequest */
3+
/* global require */
4+
/* global module */
35
"use strict";
46

57
// module Network.HTTP.Affjax
68

79
// jshint maxparams: 5
810
exports._ajax = function (mkHeader, options, canceler, errback, callback) {
11+
var platformSpecific = { };
12+
if (typeof module !== "undefined" && module.exports) {
13+
// We are on node.js
14+
platformSpecific.newXHR = function () {
15+
var XHR = require("xmlhttprequest").XMLHttpRequest;
16+
return new XHR();
17+
};
18+
19+
platformSpecific.fixupUrl = function (url) {
20+
var urllib = require("url");
21+
var u = urllib.parse(url);
22+
u.protocol = u.protocol || "http:";
23+
u.hostname = u.hostname || "localhost";
24+
return urllib.format(u);
25+
};
26+
27+
platformSpecific.getResponse = function (xhr) {
28+
// the node package 'xmlhttprequest' does not support xhr.response.
29+
return xhr.responseText;
30+
};
31+
} else {
32+
// We are in the browser
33+
platformSpecific.newXHR = function () {
34+
return new XMLHttpRequest();
35+
};
36+
37+
platformSpecific.fixupUrl = function (url) {
38+
return url || "/";
39+
};
40+
41+
platformSpecific.getResponse = function (xhr) {
42+
return xhr.response;
43+
};
44+
}
45+
946
return function () {
10-
var xhr = new XMLHttpRequest();
11-
xhr.open(options.method || "GET", options.url || "/", true, options.username, options.password);
47+
var xhr = platformSpecific.newXHR();
48+
var fixedUrl = platformSpecific.fixupUrl(options.url);
49+
xhr.open(options.method || "GET", fixedUrl, true, options.username, options.password);
1250
if (options.headers) {
1351
for (var i = 0, header; (header = options.headers[i]) != null; i++) {
1452
xhr.setRequestHeader(header.field, header.value);
@@ -28,7 +66,7 @@ exports._ajax = function (mkHeader, options, canceler, errback, callback) {
2866
var i = header.indexOf(":");
2967
return mkHeader(header.substring(0, i))(header.substring(i + 2));
3068
}),
31-
response: xhr.response
69+
response: platformSpecific.getResponse(xhr)
3270
})();
3371
};
3472
xhr.responseType = options.responseType;

0 commit comments

Comments
 (0)