diff --git a/index.js b/index.js index b096476..62a485e 100644 --- a/index.js +++ b/index.js @@ -195,7 +195,9 @@ function got(url, opts, cb) { readAllStream(res, encoding, function (err, data) { if (err) { err = new GotError('Reading ' + url + ' response failed', err); - } else if (json) { + } else if (json && statusCode !== 204) { + // only parse json if the option is enabled, and the response + // is not a 204 (empty reponse) try { data = JSON.parse(data); } catch (e) { diff --git a/test/test-json.js b/test/test-json.js index cd67fd1..86fcbd3 100644 --- a/test/test-json.js +++ b/test/test-json.js @@ -12,6 +12,11 @@ s.on('/invalid', function (req, res) { res.end('/'); }); +s.on('/204', function (req, res) { + res.statusCode = 204; + res.end(); +}); + s.on('/non200', function (req, res) { res.statusCode = 500; res.end('{"data":"dog"}'); @@ -43,6 +48,13 @@ test('json option should parse response', function (t) { }); }); +test('json option should not parse responses without a body', function (t) { + got(s.url + '/204', {json: true}, function (err) { + t.error(err); + t.end(); + }); +}); + test('json option wrap parsing errors', function (t) { got(s.url + '/invalid', {json: true}, function (err) { t.ok(err);