forked from kriszyp/commonjs-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsgi-client.js
51 lines (49 loc) · 1.43 KB
/
jsgi-client.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
/**
* HTTP Client using the JSGI standard objects
*/
var defer = require("promised-io/promise").defer;
exports.request = function(request){
var xhr = new XMLHttpRequest();
xhr.open(request.method || "GET",
request.uri || // allow request.uri to shortcut creating a URL from all the various parts
(request.scheme + "://" + request.serverName + ":" + request.serverPort + request.pathInfo + (request.queryString ? '?' + request.queryString : '')), true);
for(var i in request.headers){
xhr.setRequestHeader(i, request.headers[i]);
}
var deferred = defer();
var response;
var lastUpdate;
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 || xhr.readyState == 3){
if(!response){
response = {
body: [xhr.responseText],
status: xhr.status,
headers: {}
};
lastUpdate = xhr.responseText.length;
var headers = xhr.getAllResponseHeaders();
headers = headers.split(/\n/);
for(var i = 0; i < headers.length; i++){
var nameValue = headers[i].split(": ", 2);
if(nameValue){
var name = nameValue[0];
response.headers[name.toLowerCase()] = xhr.getResponseHeader(name);
}
}
}
else{
response.body = [xhr.responseText];
lastUpdate = xhr.responseText.length;
}
if(xhr.readyState == 4){
deferred.resolve(response);
}
else{
deferred.progress(response);
}
}
}
xhr.send(request.body && request.body.toString());
return deferred.promise;
}