Skip to content

Commit

Permalink
fix: deal while sending an empty body as a buffer (#4797)
Browse files Browse the repository at this point in the history
  • Loading branch information
strelov1 committed Jun 14, 2023
1 parent 1128dc0 commit 1a6597f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/contentTypeParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ function getDefaultJsonParser (onProtoPoisoning, onConstructorPoisoning) {
return defaultJsonParser

function defaultJsonParser (req, body, done) {
if (body === '' || body == null) {
if (body === '' || body == null || (Buffer.isBuffer(body) && body.length === 0)) {
return done(new FST_ERR_CTP_EMPTY_JSON_BODY(), undefined)
}
let json
Expand Down
51 changes: 51 additions & 0 deletions test/buffer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const t = require('tap')
const test = t.test
const Fastify = require('..')

test('Buffer test', async t => {
const fastify = Fastify()
fastify.addContentTypeParser('application/json', { parseAs: 'buffer' }, fastify.getDefaultJsonParser('error', 'ignore'))

fastify.delete('/', async (request) => {
return request.body
})

test('should return 200 if the body is not empty', async t => {
t.plan(3)

const response = await fastify.inject({
method: 'DELETE',
url: '/',
payload: Buffer.from('{"hello":"world"}'),
headers: {
'content-type': 'application/json'
}
})

t.error(response.error)
t.equal(response.statusCode, 200)
t.same(response.payload.toString(), '{"hello":"world"}')
})

test('should return 400 if the body is empty', async t => {
t.plan(3)

const response = await fastify.inject({
method: 'DELETE',
url: '/',
payload: Buffer.alloc(0),
headers: {
'content-type': 'application/json'
}
})

t.error(response.error)
t.equal(response.statusCode, 400)
t.same(JSON.parse(response.payload.toString()), {
error: 'Bad Request',
code: 'FST_ERR_CTP_EMPTY_JSON_BODY',
message: 'Body cannot be empty when content-type is set to \'application/json\'',
statusCode: 400
})
})
})

0 comments on commit 1a6597f

Please sign in to comment.