Skip to content

Commit

Permalink
fix: set content-length when using FormData body w/ request (nodejs#2066
Browse files Browse the repository at this point in the history
)

* fix: set content-length when using FormData body w/ request

* import FormData
  • Loading branch information
KhafraDev authored and crysmags committed Feb 27, 2024
1 parent d836878 commit 91913f9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/core/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ class Request {
this.headers += `content-type: ${contentType}\r\n`
}
this.body = bodyStream.stream
this.contentLength = bodyStream.length
} else if (util.isBlobLike(body) && this.contentType == null && body.type) {
this.contentType = body.type
this.headers += `content-type: ${body.type}\r\n`
Expand Down
30 changes: 30 additions & 0 deletions test/issue-2065.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict'

const { test, skip } = require('tap')
const { nodeMajor, nodeMinor } = require('../lib/core/util')
const { createServer } = require('http')
const { once } = require('events')
const { File, FormData, request } = require('..')

if (nodeMajor < 16 || (nodeMajor === 16 && nodeMinor < 8)) {
skip('FormData is not available in node < v16.8.0')
process.exit()
}

test('undici.request with a FormData body should set content-length header', async (t) => {
const server = createServer((req, res) => {
t.ok(req.headers['content-length'])
res.end()
}).listen(0)

t.teardown(server.close.bind(server))
await once(server, 'listening')

const body = new FormData()
body.set('file', new File(['abc'], 'abc.txt'))

await request(`http://localhost:${server.address().port}`, {
method: 'POST',
body
})
})

0 comments on commit 91913f9

Please sign in to comment.