Skip to content

Commit

Permalink
fix: empty bodies does not crash anymore (#420)
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette authored Mar 6, 2023
1 parent 23666d9 commit 5109dce
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,10 @@ function fastifyMultipart (fastify, options, done) {
async function saveRequestFiles (options) {
let files
if (attachFieldsToBody === true) {
// Skip the whole process if the body is empty
if (!this.body) {
return []
}
files = filesFromFields.call(this, this.body)
} else {
files = await this.files(options)
Expand Down
50 changes: 50 additions & 0 deletions test/multipart-empty-body.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict'

const test = require('tap').test
const FormData = require('form-data')
const Fastify = require('fastify')
const multipart = require('..')
const http = require('http')
const { once } = require('events')

test('should not break with a empty request body when attachFieldsToBody is true', async function (t) {
t.plan(5)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

fastify.register(multipart, { attachFieldsToBody: true })

fastify.post('/', async function (req, reply) {
t.ok(req.isMultipart())

const files = await req.saveRequestFiles()

t.ok(Array.isArray(files))
t.equal(files.length, 0)

reply.code(200).send()
})

await fastify.listen({ port: 0 })

// request
const form = new FormData()
const opts = {
protocol: 'http:',
hostname: 'localhost',
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}

const req = http.request(opts)
form.pipe(req)

const [res] = await once(req, 'response')
t.equal(res.statusCode, 200)
res.resume()
await once(res, 'end')
t.pass('res ended successfully')
})

0 comments on commit 5109dce

Please sign in to comment.