Skip to content

Commit

Permalink
fix: x-www-form-urlencoded parser keep the BOM
Browse files Browse the repository at this point in the history
  • Loading branch information
cola119 committed Jul 19, 2022
1 parent 76f6627 commit 55399bf
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
13 changes: 12 additions & 1 deletion lib/fetch/body.js
Expand Up @@ -404,7 +404,18 @@ function bodyMixinMethods (instance) {
// 1. Let entries be the result of parsing bytes.
let entries
try {
entries = new URLSearchParams(await this.text())
let text = ''
// application/x-www-form-urlencoded parser will keep the BOM.
// https://url.spec.whatwg.org/#concept-urlencoded-parser
const textDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
for await (const chunk of consumeBody(this[kState].body)) {
if (!isUint8Array(chunk)) {
throw new TypeError('Expected Uint8Array chunk')
}
text += textDecoder.decode(chunk, { stream: true })
}
text += textDecoder.decode()
entries = new URLSearchParams(text)
} catch (err) {
// istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
// 2. If entries is failure, then throw a TypeError.
Expand Down
36 changes: 36 additions & 0 deletions test/fetch/client-fetch.js
Expand Up @@ -202,6 +202,42 @@ test('urlencoded formData', (t) => {
})
})

test('text with BOM', (t) => {
t.plan(1)

const server = createServer((req, res) => {
res.setHeader('content-type', 'application/x-www-form-urlencoded')
res.end('\uFEFFtest=\uFEFF')
})
t.teardown(server.close.bind(server))

server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.text())
.then(text => {
t.equal(text, 'test=\uFEFF')
})
})
})

test('formData with BOM', (t) => {
t.plan(1)

const server = createServer((req, res) => {
res.setHeader('content-type', 'application/x-www-form-urlencoded')
res.end('\uFEFFtest=\uFEFF')
})
t.teardown(server.close.bind(server))

server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.formData())
.then(formData => {
t.equal(formData.get('\uFEFFtest'), '\uFEFF')
})
})
})

test('locked blob body', (t) => {
t.plan(1)

Expand Down

0 comments on commit 55399bf

Please sign in to comment.