Skip to content
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
6 changes: 4 additions & 2 deletions backbone.fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
};

var getData = function(response, dataType) {
return dataType === 'json' ? response.json() : response.text();
return dataType === 'json' && response.status !== 204 ? response.json() : response.text();
};

var ajax = function(options) {
Expand All @@ -49,7 +49,9 @@

return fetch(options.url, options)
.then(function(response) {
var promise = getData(response, options.dataType);
var promise = options.type === 'HEAD'
? Promise.resolve(null)
: getData(response, options.dataType);

if (response.ok) return promise;

Expand Down
32 changes: 32 additions & 0 deletions test/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,38 @@ describe('backbone.fetch', function() {
return promise;
});

it('should produce an error for invalid json', function(done) {
var promise = ajax({
dataType: 'json',
url: 'test',
type: 'GET',
});

promise.then(function() {
throw new Error('this request should fail');
}).catch(function(error) {
expect(error).to.be.an.instanceof(SyntaxError);
expect(error).not.to.have.property('response');
done();
}).catch(function(error) {
done(error);
});

server.respond([200, {}, '']);
return promise;
});

it('should not parse json for 204 responses', function() {
var promise = ajax({
dataType: 'json',
url: 'test',
type: 'GET',
});

server.respond([204, {}, '']);
return promise;
});

it('should parse json as property of Error on failing request', function(done) {
var promise = ajax({
dataType: 'json',
Expand Down