fetch
fetch copied to clipboard
Bug: When headers is native Headers object, they won't get send
Steps to Reproduce
Code: https://codesandbox.io/s/determined-cdn-7k3gx?file=/src/index.js App: https://7k3gx.csb.app/
Theories
We do new Headers(options.headers)
:
https://github.com/github/fetch/blob/75d9455d380f365701151f3ac85c5bda4bbbde76/fetch.js#L367-L369
Which will use the local polyfill function Headers
which is also what this line will check against:
https://github.com/github/fetch/blob/75d9455d380f365701151f3ac85c5bda4bbbde76/fetch.js#L86-L90
But if options.headers
is the builtin Headers
object, the instanceof check will fail, as well as the fallback case because getOwnPropertyNames()
will return an empty object:
https://github.com/github/fetch/blob/75d9455d380f365701151f3ac85c5bda4bbbde76/fetch.js#L94-L98
Solution
Don't polyfill Headers
when there's a builtin, native version.
I came across the problem, too. Before I saw this Issue, it took a few debugging sessions stepping through the code to discover that, indeed, the if (headers instanceof Headers)
checks fails when unknowingly using the native Headers
object.
Attempting to use an Array doesn't work neither because !(init.headers instanceof Headers)
in
https://github.com/github/fetch/blob/a8aa427de0ed808ff26c0e3eb2e59c122c44488a/fetch.js#L573-L581
...evaluates to true
and the execution goes through the if
block, and the header elements end up being somethig like 0: accept, application/json
(0
is the index in the array) for something that should be accept: application/json
.
What worked was to alias polyfill's Headers
. For example:
import { Headers as FetchPolyfillHeaders } from 'whatwg-fetch';
...and use FetchPolyfillHeaders
everywhere in the code.
Hope this helps.
@FokkeZB and/or @apisim -- Which browser or runtime has Headers
defined but does not have fetch
defined?
Resolved via https://github.com/JakeChampion/fetch/pull/1358