Skip to content

Commit 2676c94

Browse files
committed
Skip content-length header for entries without known length when enableAdditionalHeaders option is enabled
1 parent 9ca70ed commit 2676c94

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/FormDataEncoder.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,41 @@ test(
399399
}
400400
)
401401

402+
test(
403+
"Does not imclude Content-Length header with enableAdditionalHeaders "
404+
+ "option if entry does not have known length",
405+
406+
async t => {
407+
const form = new FormData()
408+
409+
form.set("stream", {
410+
[Symbol.toStringTag]: "File",
411+
name: "file.txt",
412+
stream() {
413+
return Readable.from([Buffer.from("foo")])
414+
}
415+
})
416+
417+
const encoder = new FormDataEncoder(form, {
418+
enableAdditionalHeaders: true
419+
})
420+
421+
const iterable = readLine(Readable.from(encoder))
422+
423+
await skip(iterable, 1)
424+
const headers: string[] = []
425+
for await (const chunk of iterable) {
426+
if (chunk === "") {
427+
break
428+
}
429+
430+
headers.push(chunk.split(":")[0].toLowerCase())
431+
}
432+
433+
t.false(headers.includes("content-length"))
434+
}
435+
)
436+
402437
test("Yields File's content", async t => {
403438
const filePath = "license"
404439
const form = new FormData()

src/FormDataEncoder.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable no-restricted-globals */
12
import type {LowercaseObjectKeys} from "./util/LowercaseObjectKeys.js"
23
import {createBoundary} from "./util/createBoundary.js"
34
import {normalizeValue} from "./util/normalizeValue.js"
@@ -207,7 +208,11 @@ export class FormDataEncoder {
207208
}
208209

209210
const size = isFile(value) ? value.size : value.byteLength
210-
if (this.#options.enableAdditionalHeaders === true && size != null) {
211+
if (
212+
this.#options.enableAdditionalHeaders === true
213+
&& size != null
214+
&& !isNaN(size)
215+
) {
211216
header += `${this.#CRLF}Content-Length: ${
212217
isFile(value) ? value.size : value.byteLength
213218
}`
@@ -230,7 +235,7 @@ export class FormDataEncoder {
230235
const size = isFile(value) ? value.size : value.byteLength
231236

232237
// Return `undefined` if encountered part without known size
233-
if (size == null || Number.isNaN(size)) {
238+
if (size == null || isNaN(size)) {
234239
return undefined
235240
}
236241

0 commit comments

Comments
 (0)