Skip to content

Commit

Permalink
Merge pull request #2 from gergelyke/master
Browse files Browse the repository at this point in the history
Handling empty responses in the json parser
  • Loading branch information
vesln committed Jan 14, 2014
2 parents 8d60c95 + 8b43e34 commit 4b4e36e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/hippie/parsers.js
@@ -1,7 +1,7 @@
/**
* Parse JSON.
*
* @param {Object} data
* @param {Object} data - if empty(eg: HTTP 204, HTTP 304) then not parsed
* @param {Function} fn
* @api public
*/
Expand All @@ -10,10 +10,12 @@ exports.json = function(data, fn) {
var res = null;
var err = null;

try {
res = JSON.parse(data);
} catch (e) {
err = e;
if (data) {
try {
res = JSON.parse(data);
} catch (e) {
err = e;
}
}

fn(err, res);
Expand Down
8 changes: 8 additions & 0 deletions test/json.test.js
Expand Up @@ -38,4 +38,12 @@ describe('#json', function() {
done();
});
});

it('works fine if the response is empty', function(done) {
api()
.json()
.get('/empty-response')
.expectStatus(204)
.end(done);
});
});
4 changes: 4 additions & 0 deletions test/support/server.js
Expand Up @@ -32,6 +32,10 @@ app.post('/send-json', express.json(), function(req, res) {
res.send(JSON.stringify(req.body));
});

app.get('/empty-response', function(req, res) {
res.send(204);
});

app.get('/auth', express.basicAuth('user', 'pass'), function(req, res) {
res.send('ok');
});
Expand Down

0 comments on commit 4b4e36e

Please sign in to comment.