lquixada / cross-fetch

Universal WHATWG Fetch API for Node, Browsers and React Native.
MIT License
1.67k stars 104 forks source link

Browser ponyfill causes issues if you forget to import { Headers } #92

Closed asztal closed 3 years ago

asztal commented 3 years ago

How to reproduce this issue:

import fetch from "cross-fetch"; // Oops! Forgot to import { Headers } as well!

const headers = new Headers({ "X-Requested-With": "..." });
fetch("https://example.com", { headers }); 

In my case, the X-Requested-With header was not added to the request.

Arguably, this example is incorrect because I should have written import fetch, { Headers } from "cross-fetch". If I do that, my example works. But I think it's worth either adding import fetch, { Headers } to the examples or finding a better way to implement this instanceof check, because it took me a long time to debug this issue (I suspected it was a problem with my CORS headers on my server).

lquixada commented 3 years ago

I guess what might be happening here is that your code must be adding a Headers constructor as a global variable at some point. That global constructor would not be the same as the one cross-fetch provides, thus the headers instanceof Headers would resolve to false. And because of that, the header in question is not added in the final request.

Since this feels like a particular case on your end, it doesn't seem adding that example to the docs would be helpful to the general user.

asztal commented 3 years ago

Hi, I wasn't adding a Headers constructor of my own - I simply wasn't importing Headers from cross-fetch, so I was getting the browser's built-in Headers class rather than cross-fetch's. But because cross-fetch is using instanceof, cross-fetch only accepts its own Headers class (not the browser's built-in one).

lquixada commented 3 years ago

got it! thanks for reporting that edge case! A couple of things here: