From 416bb7b00f1585ea028d0ce051332fd4541870d1 Mon Sep 17 00:00:00 2001 From: Eli Skeggs Date: Thu, 3 Sep 2020 16:55:13 -0700 Subject: [PATCH 1/2] fix: add head, 204 parser handling This behavior improves jquery compatibility. See https://github.com/jquery/jquery/blob/df6858df2ed3fc5c424591a5e09b900eb4ce0417/src/ajax.js#L762-L780 --- backbone.fetch.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/backbone.fetch.js b/backbone.fetch.js index 542d33d..7c5449b 100644 --- a/backbone.fetch.js +++ b/backbone.fetch.js @@ -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) { @@ -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; From b8ab4eca1896d71a2dc68aa4a9a3a7b90c2945d8 Mon Sep 17 00:00:00 2001 From: Eli Skeggs Date: Fri, 4 Sep 2020 11:46:49 -0700 Subject: [PATCH 2/2] test: verify malformed json handling --- test/fetch.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/test/fetch.js b/test/fetch.js index db8d076..0b2115c 100644 --- a/test/fetch.js +++ b/test/fetch.js @@ -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',