Skip to content

Commit 7741ba1

Browse files
authored
Merge pull request #20 from canjs/handle-204-no-content-on-json-requests
Handle 204 No Content responses when expecting JSON
2 parents 86fb4ca + cc846b1 commit 7741ba1

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

can-ajax-test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,44 @@ QUnit.test("crossDomain is true for relative requests", function (assert) {
414414
});
415415
});
416416

417+
QUnit.test("handles 204 No Content responses when expecting JSON", function (assert) {
418+
var done = assert.async();
419+
var headers = {},
420+
restore = makeFixture(function () {
421+
this.open = function (type, url) {};
422+
423+
this.send = function () {
424+
this.readyState = 4;
425+
this.status = 204;
426+
this.responseText = '';
427+
this.onreadystatechange();
428+
};
429+
430+
this.setRequestHeader = function (header, value) {
431+
headers[header] = value;
432+
};
433+
});
434+
435+
ajax({
436+
type: "delete",
437+
url: "/foo",
438+
data: {
439+
id: "qux"
440+
},
441+
dataType: "json"
442+
}).then(function () {
443+
assert.deepEqual(headers, {
444+
"Content-Type": "application/json",
445+
"X-Requested-With": "XMLHttpRequest"});
446+
}, function (reason) {
447+
assert.notOk(reason, "request failed with reason = ", reason);
448+
}).then(function () {
449+
// restore original values
450+
restore();
451+
done();
452+
});
453+
});
454+
417455
if (hasLocalServer) {
418456
QUnit.test("correctly serializes null and undefined values (#177)", function (assert) {
419457
var done = assert.async();

can-ajax.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ var _xhrResp = function (xhr, options) {
111111
case "application/javascript":
112112
case "application/x-javascript":
113113
case "json":
114-
return JSON.parse(xhr.responseText);
114+
return xhr.responseText && JSON.parse(xhr.responseText);
115115
default:
116116
return xhr.responseText;
117117
}

0 commit comments

Comments
 (0)