Skip to content

Commit

Permalink
fix(Request): allow passing Headers instance to init.headers (nodejs#…
Browse files Browse the repository at this point in the history
…1401)

* fix(Request): allow passing Headers instance to init.headers

* fix(Request): remove unnecessary condition

* test: fix node-fetch test failures

* fixup

Co-authored-by: Robert Nagy <ronagy@icloud.com>
  • Loading branch information
2 people authored and metcoder95 committed Dec 26, 2022
1 parent d273745 commit 5fd66ca
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 13 deletions.
17 changes: 5 additions & 12 deletions lib/fetch/request.js
Expand Up @@ -419,16 +419,10 @@ class Request {

// 4. If headers is a Headers object, then for each header in its header
// list, append header’s name/header’s value to this’s headers.
if (headers instanceof Headers) {
// TODO (fix): Why doesn't this work?
// for (const [key, val] of headers[kHeadersList]) {
// this[kHeaders].append(key, val)
// }

this[kState].headersList = new HeadersList([
...this[kState].headersList,
...headers[kHeadersList]
])
if (headers.constructor.name === 'Headers') {
for (const [key, val] of headers[kHeadersList] || headers) {
this[kHeaders].append(key, val)
}
} else {
// 5. Otherwise, fill this’s headers with headers.
fillHeaders(this[kState].headersList, headers)
Expand Down Expand Up @@ -467,8 +461,7 @@ class Request {
// not contain `Content-Type`, then append `Content-Type`/Content-Type to
// this’s headers.
if (contentType && !this[kHeaders].has('content-type')) {
this[kHeaders].set('content-type', contentType)
this[kState].headersList.set('content-type', contentType)
this[kHeaders].append('content-type', contentType)
}
}

Expand Down
35 changes: 34 additions & 1 deletion test/fetch/request.js
Expand Up @@ -4,7 +4,8 @@

const { test } = require('tap')
const {
Request
Request,
Headers
} = require('../../')
const { kState } = require('../../lib/fetch/symbols.js')
const { URLSearchParams } = require('url')
Expand Down Expand Up @@ -294,3 +295,35 @@ test('post aborted signal cloned', t => {
})
ac.abort()
})

test('Passing headers in init', (t) => {
// https://github.com/nodejs/undici/issues/1400
t.test('Headers instance', (t) => {
const req = new Request('http://localhost', {
headers: new Headers({ key: 'value' })
})

t.equal(req.headers.get('key'), 'value')
t.end()
})

t.test('key:value object', (t) => {
const req = new Request('http://localhost', {
headers: { key: 'value' }
})

t.equal(req.headers.get('key'), 'value')
t.end()
})

t.test('[key, value][]', (t) => {
const req = new Request('http://localhost', {
headers: [['key', 'value']]
})

t.equal(req.headers.get('key'), 'value')
t.end()
})

t.end()
})

0 comments on commit 5fd66ca

Please sign in to comment.