Skip to content

Commit

Permalink
accept empty response in JSON mode. Returned data is null in this…
Browse files Browse the repository at this point in the history
… case.
  • Loading branch information
dgrelaud committed Apr 17, 2023
1 parent e049fb2 commit 692fea4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Rock-req

### 5.1.1
- Accept empty response in JSON mode. Returned `data` is `null` in this case.

### 5.1.0
- Add benchmark and replace NodeJS `pipeline` by traditional `pipe` (x2 faster)
- Add default keep alive
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ function extend (defaultOptions = {}) {
}
let data = Buffer.concat(chunks)
if (opts.json) {
try { data = JSON.parse(data.toString()) } catch (e) { return cb(e, response, data) }
try { data = data.length > 0 ? JSON.parse(data.toString()) : null } catch (e) { return cb(e, response, data) }
}
cb(null, response, data)
}
Expand Down
29 changes: 29 additions & 0 deletions test/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,35 @@ test('post (json body)', function (t) {
})
})

test('post with empty JSON response should not crash', function (t) {
t.plan(5)

const server = http.createServer(function (req, res) {
t.equal(req.method, 'POST')
t.equal(req.headers['content-type'], 'application/json')
res.statusCode = 204
res.end();
})

server.listen(0, function () {
const port = server.address().port
const opts = {
method: 'POST',
url: 'http://localhost:' + port,
body: {
message: 'this is the body'
},
json: true
}
rock.concat(opts, function (err, res, data) {
t.error(err)
t.equal(res.statusCode, 204)
t.equal(data, null)
server.close()
})
})
})

test('should accept postJSON as a shortcut', function (t) {
t.plan(5)

Expand Down

0 comments on commit 692fea4

Please sign in to comment.