Skip to content
This repository was archived by the owner on Apr 4, 2019. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,25 @@ function json(url, obj, headers, fn){
if (3 == arguments.length) fn = headers, headers = {};

var req = new XMLHttpRequest;
req.onerror = fn;
req.onreadystatechange = done;
req.onerror = error;
req.onload = done;
req.open('POST', url, true);
for (var k in headers) req.setRequestHeader(k, headers[k]);
req.send(JSON.stringify(obj));

function done(){
if (4 == req.readyState) return fn(null, req);
// sometimes IE returns 1223 when it should be 204
// see http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
if (/^(20\d|1223)$/.test(req.status)) {
return fn(null, req)
}
fn(new Error("Request wasn't successful"), req);
}

function error(event){
var err = new Error("A network error ocurred");
err.event = event;
fn(err);
}
}

Expand Down
23 changes: 23 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,29 @@ describe('send-json', function(){
done();
});
})

it('should invoke the callback with an error when connection is refused', function(done){
if ('xhr' != send.type) return done();
var url = protocol() + '//localhost:4567/data';
var headers = { 'Content-Type': 'application/json' };
send.json(url, [1, 2, 3], headers, function(err, req){
assert(err);
assert(typeof err.event === "object");
done();
});
})

it('should invoke the callback with an error when the request does not succeed', function(done){
if ('xhr' != send.type) return done();
var url = protocol() + '//localhost:3001/not-found';
var headers = { 'Content-Type': 'application/json' };
send.json(url, [1, 2, 3], headers, function(err, req){
assert(err);
assert(typeof req === "object");
assert(req.status === 404);
done();
});
})
})

describe('#base64', function(){
Expand Down