Skip to content

Commit

Permalink
do not parse json on a 204 response
Browse files Browse the repository at this point in the history
  • Loading branch information
Connor Hindley committed Jun 30, 2015
1 parent 3c728bc commit 312c80d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions test/test-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"}');
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 312c80d

Please sign in to comment.