lquixada / cross-fetch Goto Github PK
View Code? Open in Web Editor NEWUniversal WHATWG Fetch API for Node, Browsers and React Native.
License: MIT License
Universal WHATWG Fetch API for Node, Browsers and React Native.
License: MIT License
Hi there,
Thanks a lot for this project.
Could you please update GitHub releases? I use them to automatically check for new versions with my RSS reader.
Thanks!
https://github.com/jhen0409/react-native-debugger is a pretty popular tool to debug RN apps.
If you enable network inspect inside react-native-debugger
and make a fetch()
call via cross-fetch
and the server responds with JSON, the response is converted to the literal string "[object Blob]
.
This issue has been brought up in react-native-debugger before, and the authors essentially say when this happens "you are referencing the wrong fetch". See: jhen0409/react-native-debugger#440 (comment)
getting this in Chrome when sending Connection: keep alive
in the request options for headers.
any idea on this?
Hi there -- I believe I am trying to use cross-fetch
beyond it's intended means and am looking for a confirmation before I give up and pursue other solutions. Essentially, I'm trying to make an npm package that can run on both Nodejs and the browser.
So the assumption was that I could use import fetch from 'cross-fetch'
and have that provide the appropriate fetch regardless of the environment. After bundling, it works fine on the browser, but I'm receive a reference error: ReferenceError: XMLHttpRequest is not defined
when I try to require the output in Nodejs. A cursory look at the bundle output seems to indicate it is using the browser ponyfill, something that looks like it might be decide at bundle time?
I've made a small repo here to show my current configuration. The current alternative solution for me would be to just label cross-fetch
as an external module in the bundling process, import it manually in node environments as a polyfill, and rely on the native browser fetch
when it comes to the browser environments.
// Nodejs
import 'cross-fetch/polyfill';
import { doAFetchCall } from 'mylib';
// Browser
import { doAFetchCall } from 'mylib';
Please let me know if there's maybe a better way to handle this, your input on the preferred usage would be great ๐
Thanks!
There's a long discussion at whatwg/fetch#37 about user-agent, which apparently is no longer forbidden.
Is that header still ignored by cross-fetch
? The following sent a user agent of node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
.
fetch(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Mobile Safari/537.36', // Chrome Android, to maybe get a slimmer page version
},
})
Then the code can be used with https://www.npmjs.com/package/esm ๐
node-fetch/lib/index.js is not really compatible with ie11 because class is not recognizable by browser.
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "../node_modules/webpack/buildin/module.js")(module)))
/***/ }),
/***/ "../node_modules/node-fetch/lib/index.js":
/*!***********************************************!*\
!*** ../node_modules/node-fetch/lib/index.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer, global) {
Object.defineProperty(exports, '__esModule', { value: true });
// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
// (MIT licensed)
const BUFFER = Symbol('buffer');
const TYPE = Symbol('type');
class Blob {
constructor() {
this[TYPE] = '';
const blobParts = arguments[0];
const options = arguments[1];
const buffers = [];
if (blobParts) {
Are errors handled the same way between node-fetch
and whatwg-fetch
?
Do this lib ensure this?
Maybe this is just me having issues with my configuration but I have a lib that I want to use in my RN app.
When I bundle it, it brings node-fetch which needs node deps
(!) Unresolved dependencies
https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency
stream (imported by node_modules/node-fetch/lib/index.js, node_modules/iconv-lite/lib/streams.js, node_modules/iconv-lite/lib/extend-node.js, commonjs-external:stream)
url (imported by node_modules/node-fetch/lib/index.js, commonjs-external:url)
https (imported by node_modules/node-fetch/lib/index.js, commonjs-external:https)
http (imported by node_modules/node-fetch/lib/index.js, commonjs-external:http)
zlib (imported by node_modules/node-fetch/lib/index.js, commonjs-external:zlib)
buffer (imported by node_modules/safer-buffer/safer.js, node_modules/safe-buffer/index.js, node_modules/iconv-lite/lib/streams.js, node_modules/iconv-lite/lib/extend-node.js, commonjs-external:buffer)
Then in RN the bundler complain about those deps not being in the haste map
bundling failed: Error: Unable to resolve module `buffer` from `/Users/nhauseux/Dev/perso/NativeSleep/node_modules/yarec/dist/index.umd.js`: Module `buffer` does not exist in the Haste module map
If I remove cross-fetch pony/polyfill and bundle again, it works fine in RN. (but as i'd like the lib to work everywhere this is still a problem)
Any clue how to solve this ?
Hi there, I am trying to use cross-fetch to replace isomorohic-fetch.
We need to support all browsers and IOS/Android through React Native.
Just noticed this. Could you please help.
https://www.npmjs.com/package/cross-fetch#supported-environments
When options.headers
already is a native Headers
object, this will lead to an empty this.headers
:
cross-fetch/dist/browser-ponyfill.js
Lines 346 to 348 in 2257827
This is because the instanceof
check here is done against the polyfil:
cross-fetch/dist/browser-ponyfill.js
Lines 93 to 96 in 2257827
We should either not override Headers
if it already exists, or keep a reference to the original and include it in the instanceof
check as well.
Please publish a new version of this package with an updated dependency on node-fetch
to be 2.6.1 or greater. This will avoid the vulnerability described here:
Hi,
I'm c8y/client, in that they are using the cross-fetch. I don't know for some reason i get this error, when i checked the node modules, i would see the cross-fetch.
But i'm not sure what is this error, if possible could you please give me some insight on this error
ERROR in node_modules/@c8y/client/lib/src/core/FetchClient.d.ts(2,27): error TS7016: Could not find a declaration file for module 'cross-fetch'. 'C:/Projects/angular-its-code/node_modules/cross-fetch/dist/node-ponyfill.js' implicitly has an 'any' type.
Try `npm install @types/cross-fetch` if it exists or add a new declaration (.d.ts) file containing `declare module 'cross-fetch';`
node_modules/@c8y/client/lib/src/core/IAuthentication.d.ts(10,5): error TS2411: Property 'tenant' of type 'string | undefined' is not assignable to string index type 'string'.
node_modules/@c8y/client/lib/src/core/IAuthentication.d.ts(11,5): error TS2411: Property 'user' of type 'string | undefined' is not assignable to string index type 'string'.
node_modules/@c8y/client/lib/src/core/IAuthentication.d.ts(12,5): error TS2411: Property 'password' of type 'string | undefined' is not assignable to string index type 'string'.
node_modules/@c8y/client/lib/src/core/IAuthentication.d.ts(13,5): error TS2411: Property 'token' of type 'string | undefined' is not assignable to string index type 'string'.
node_modules/@c8y/client/lib/src/core/IAuthentication.d.ts(14,5): error TS2411: Property 'tfa' of type 'string | undefined' is not assignable to string index type 'string'.
I send a fetch requesh follow:
const payload = computePayload(options, token, tenant);
const response = await fetch(`https://${getServer(host, port)}/${endpoint}`, payload);
When I use isomorphic-fetch
it works as excpected, but when I switch to cross-fetch
this fails.
cross-fetch
and Headers()
failsWhere computePayload()
create a headers oject like:
options.headers = new Headers({
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Auth-token': token,
});
The resulting request is:
fetch('https://wazo/api/confd/1.0/resellers/f1e32efc-7d6b-4797-879e-7dfa03aa3023', {
credentials: 'omit',
referrer: 'http://localhost:3000/',
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
mode: 'cors',
});
headers
is missing :/
cross-fetch
and object literalA workaround is to use a literal object instead of Headers()
:
options.headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Auth-Token': token,
};
The resulting request is:
fetch('https://wazo/api/confd/1.0/resellers/f1e32efc-7d6b-4797-879e-7dfa03aa3023', {
credentials: 'omit',
headers: {
accept: 'application/json',
'content-type': 'application/json',
'x-auth-token': 'e338eb-d66a-4f1f-87bd-22ab9834e8b',
},
referrer: 'http://localhost:3000/',
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
mode: 'cors',
});
Why is cross-fetch
not working with Headers()
?
node-fetch adds some extra fields to the fetch options interface: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node-fetch/index.d.ts#L24-L33
Would you be open to adding these here as well? The lack of the agent
field is specifically causing me trouble at the moment. Our package consumers use custom agents on the server. They don't apply to browser users.
Ideally the extra fields could be conditional based on the environment, but I am not sure of a way to do that with TypeScript.
In the latest version of the package (3.0.3) instead of a JSON response you get a buffer
{"data": [123, 34, 116, 111, 107, 101, 110, 34, 58, 34, 54, 102, 54, 56, 51, 50, 51, 49, 45, 48, 98, 48, 52, 45, 52, 102, 48, 55, 45, 97, 51, 51, 55], "type": "Buffer"}
https://www.npmjs.com/package/slim-fetch is a new library that has basically identical code to node-fetch, but stripped away unnecessary parts of the distribution (eg. node-fetch actually has three copies of the same code for backwards compatibility purposes).
I used polymer
to bundle the code, it will load the node-ponyfill.js
I know this is maybe not the intention with the library, it can just be confusing for new beginners that want to use a library that does backsupport old browser while at the same time uses just fetch with the new es module loading.
https://github.com/kevinsimper/cross-fetch-esm-test
When I make an API calls that returns a 204 (No Content) response, Instead of resolving , the promise is rejected with a TypeError: Network request failed
error. This should not be the case right. 204 responses should resolve normally only.
Hi,
Cloudflare worker provides a fetch function, however, when I'm webpacking your lib, it does seem to use XMLHttpRequest
ReferenceError: XMLHttpRequest is not defined
I did try to force webpack to use node
module.exports = {
target: "webworker",
entry: "./worker.js", // inferred from "main" in package.json
resolve: {
mainFields: ['module', 'main']
}
};
But it generates another error (global not defined)
Is there a way to force cross-fetch to to use the native fetch function?
as a proof of concept/fugly workaround, I replaced
const Fetch = fetch; //require('cross-fetch');
and it seems to work fine.
how to add timeout?
I'm using this library (via https://github.com/prisma-labs/graphql-request) and it fails to make requests when used within a browser service worker. More specifically, it throws:
ReferenceError: XMLHttpRequest is not defined
at browser-ponyfill.js:463
at new Promise (<anonymous>)
at Object.fetch [as default] (browser-ponyfill.js:455)
at GraphQLClient.<anonymous> (index.ts:87)
at step (createRequestBody.ts:45)
at Object.next (createRequestBody.ts:45)
at createRequestBody.ts:45
at new Promise (<anonymous>)
at createRequestBody.ts:45
at GraphQLClient.request (index.ts:73)
Service workers do always have fetch available, but they don't have XMLHttpRequest. See whatwg/xhr#19 for some background from the spec discussion.
Because they are a browser environment though, https://github.com/lquixada/cross-fetch/blob/master/dist/browser-ponyfill.js from this library is used, which incorrectly seems to assume XHR is always available in all modern browser environments.
I think all that's required here is to fall back to the built-in Fetch that is available in this case.
I'm getting an incorrect response when using: response.text()
More details and script here: https://hastebin.com/feloheweve.http
CORRECT TEXT RESPONSE using postman
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://InspectionService/">
<SOAP-ENV:Body>
<ns1:GetRequestResponse>
<RequestResponseResult>
<success>true</success>
<status>closed</status>
<state>7</state>
<message>Inspection Request Complete</message>
<report>https://oneguardinspections.com/components/com_rstickets/files/2020/12/22/PRCO18/PRCO-0000000018_PDF_Report.pdf</report>
</RequestResponseResult>
</ns1:GetRequestResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
ACTUAL TEXT RESPONSE from response.text()
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://InspectionService/">
<SOAP-ENV:Body>
<ns1:GetRequestResponse>
<RequestResponseResult>
<success>true</success>
<status/>
<state/>
<message/>
<report/>
</RequestResponseResult>
</ns1:GetRequestResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Just a suggestion here.
while running: npm install without lock file
Hey,
I'm currently fighting with a problem. A library we're using, airbrake-js, has cross-fetch as dependency. For some reason, when we launch the page on safari on ios 9.3.5, the page doesn't load with this cryptic message on page and no way to debug it properly. The package resolves to newest version, 3.0.3
I've tracked the issue to this package, when I don't include the other library and just include this one directly in code as:
import 'cross-fetch';
The page crashes (with debugger) while loading with no error other than the one on the screenshot. If I comment this line, it works.
What's more, when I use
import 'cross-fetch/polyfill';
It doesn't crash, so it suggests there is a problem with default export maybe?
We're using react-create-app with newest webpack version 3. We've recently migrated through react-create-app from webpack 1 to webpack 3 and there are reports it worked fine before. I would assume some kind of polyfill might be missing. Could you perhaps point me to what might be the problem (or what kind of polyfill could be missing)? I would appreciate any help!
Instead of bundling the entire whatwg-fetch, could it be a require()
call, like in isomorphic-fetch
and isomorphic-unfetch
?
The browser
field is the default entry point for all Webpack builds, which means that anyone using Webpack and accidentally including some other package that also pulls in whatwg-fetch
will get duplicate copies.
I am using this lib with a jwt based api.
It works fine for staus 200 requests but when the token expires the api returns a 401 status code. The problem is that I don't know how to retrieve the status code!
According to the docs you check status code in the (first) then
part but in my case it's skippig the then
jumping directly to the catch with a TypeError
.
How do I get the code?
Update: It works fine when I tested using node, the issue is only specific to the web browser.
Hi,
I am testing - indirectly - the cross-fetch library on CloudFlare Workers and I get the following error:
'XMLHttpRequest is not defined'
Are you planning to support CF workers in the near future ?
Please note that node-fetch seems to work with CF, but I couldn't find any "official" statement .
TIA
Would be awesome if you could publish a new npm version with the typescript definition fix? ๐ Thanks!
Its OK
Looks like node-fetch renamed its UA along with its repo from node-fetch/1.0 (+https://github.com/bitinn/node-fetch
to something without bitinn
at some point, because I can't find "bitinn" in its code.
react-native
has built-in fetch polyfills based on whatwg-fetch
already (https://github.com/facebook/react-native/blob/master/Libraries/Core/setUpXHR.js#L23-L26 some variant of this has existed over the last ~4 years or so from github history).
As such there's no real need to bundle in another fetch-ponyfill for react-native consumers. cross-fetch
can simply re-export the existing fetch function (and related types).
There also exists some timing issue where the browser ponyfill is stomping the global fetch function with false
here. The repro I've seen is in a decent sized app, while running in an iOS simulator and react-native@57
. If I run the app, then start react-native JS debugging, this causes global.fetch
to get set to false
and never unset.
$> tsc --module commonjs
node_modules/cross-fetch/index.d.ts:1:27 - error TS2304: Cannot find name 'fetch'.
1 declare const fet: typeof fetch;
~~~~~
node_modules/cross-fetch/index.d.ts:2:27 - error TS2304: Cannot find name 'Request'.
2 declare const req: typeof Request;
~~~~~~~
node_modules/cross-fetch/index.d.ts:3:27 - error TS2304: Cannot find name 'Response'.
3 declare const res: typeof Response;
~~~~~~~~
node_modules/cross-fetch/index.d.ts:4:31 - error TS2552: Cannot find name 'Headers'. Did you mean 'headers'?
4 declare const headers: typeof Headers;
~~~~~~~
node_modules/cross-fetch/index.d.ts:4:15
4 declare const headers: typeof Headers;
~~~~~~~
'headers' is declared here.
Found 4 errors.
Hi there,
I've been using cross-fetch
in a Node.js TypeScript project. When used in "non-global" form, I am seeing incorrect successful TypeScript compilation results which cause unexpected "ReferenceError" throws at runtime.
Example Project Setup:
mkdir test-project
cd test-project
yarn init
yarn add typescript cross-fetch
# specifying lib so that 'dom' isnt imported, as this is a Node project
npx tsc --init --lib es6
echo "import fetch from \"cross-fetch\";" > one.ts
echo "fetch(\"\", {});" > two.ts
Issue:
TypeScript compiles the files correctly, as the "index.d.ts" file bundled with cross-fetch
exposes the "fetch" global to both "one.ts" and "two.ts" even though it is only imported in "one.ts". I think this is because the "dom" lib is referenced here.
If I try to compile and run "two.js", I get "ReferenceError: fetch is not defined" as is expected.
npx tsc
node two.js
/Users/andrew/test-project/other-file.js:2
fetch("", {});
^
ReferenceError: fetch is not defined
at Object.<anonymous> (/Users/andrew/test-project/other-file.js:2:1)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
The correct result would be for TypeScript compilation to fail, as "fetch" should not become a project-wide global, and instead only be available in the file it is imported in.
Thanks so much for your work on cross-fetch
,
Andrew
I am using the AbortController
feature (sample) in my code, and for my jest tests which uses jest-fetch-mock
, the AbortController.abort()
method works.
In my browser I can see that a manual test of the window.fetch
works fine with the AbortController
too. But, when cross-fetch
is handling the fetch in the browser the abortcontroller signal is ignored - it seems.
I also see that there is no code in the cross-fetch project that deals with the abort-controller, and no issues mentioning it. I can see that the code supports setting the RequestInit.signal
property though. So, I was expecting it to be passed into the window.fetch()
, which I assume that cross-fetch is perhaps using under the hood - when run in the browser?
cross domain fix with jsonp request. is it possible add jsonp in cross-fetch?
I am trying to upload a csv file using cross fetch with react-redux and I am getting Uncaught (in promise) Error: unsupported BodyInit type error. Full Error Trace:
Uncaught (in promise) Error: unsupported BodyInit type
at Request.Body._initBody (browser.js:227)
at new Request (browser.js:340)
at browser.js:422
at new Promise (<anonymous>)
at self.fetch (browser.js:421)
at Dropzone.RenderDropZoneInput._this.onDrop (RenderDropZoneInput.js:17)
at Dropzone.onDrop (index.js:229)
at Object.executeOnChange (LinkedValueUtils.js:132)
at ReactDOMComponent._handleChange (ReactDOMInput.js:241)
at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js:69)
at executeDispatch (EventPluginUtils.js:85)
at Object.executeDispatchesInOrder (EventPluginUtils.js:108)
at executeDispatchesAndRelease (EventPluginHub.js:43)
at executeDispatchesAndReleaseTopLevel (EventPluginHub.js:54)
at Array.forEach (<anonymous>)
at forEachAccumulated (forEachAccumulated.js:24)
at Object.processEventQueue (EventPluginHub.js:254)
at runEventQueueInBatch (ReactEventEmitterMixin.js:17)
at Object.handleTopLevel [as _handleTopLevel] (ReactEventEmitterMixin.js:27)
at handleTopLevelImpl (ReactEventListener.js:72)
at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:143)
at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
at Object.batchedUpdates (ReactUpdates.js:97)
at dispatchEvent (ReactEventListener.js:147)
Source Code:
class RenderDropZoneInput extends Component {
onDrop = (acceptedFiles, rejectedFiles) => {
const { onChange } = this.props.input
const files = this.props.input.value || Immutable.List()
const newFiles = Immutable.List(acceptedFiles)
const allFiles = files.concat(newFiles)
onChange(allFiles)
console.log(acceptedFiles);
let uri = "http://localhost:8080/api/uplaod"
fetch(uri, {
method: 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/octet-stream' },
body: acceptedFiles[0]
})
}
render() {
const files = this.props.input.value
return (
<div>
<CustomDropzone onDrop={this.onDrop} multiple={true}>
{files.size ?
files.map((file) => <img key={file.name} src={file.preview} style={{ width: '200px', maxWidth: '400px', flexGrow: 1, opacity: 0.5 }} alt='' />)
: <div><p>Click on me!</p></div>}
</CustomDropzone>
</div>
)
}
}
export default RenderDropZoneInput
You can reproduce or access full project here: https://codesandbox.io/s/z39y9mlwq4
Steps to reproduce: Try uploading a file, the error will be displayed.
I have also tried using FormData
let form = new FormData()
form.append('file', acceptedFiles[0]);
return fetch(uri, {
method: 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/octet-stream' },
body: form//acceptedFiles[0]
})
I've written an API wrapper that uses cross-fetch to make it compatible with Browsers, Node and React Native. Now, if I test it with Node it works perfectly, but if I use the wrapper in React Native if fails with the following error: TypeError: undefined is not a function (evaluating 'cross_fetch_1.default(url, init)')
. If I print the type of cross_fetch_1
I get:
{ [Function]
polyfill: true,
Response: { [Function: Response] error: [Function], redirect: [Function] },
Request: [Function: Request],
Headers: [Function: Headers] }
and "undefined" for either cross_fetch_1.default
or cross_fetch_1.fetch
.
The library was developed in Typescript, so the cross_fetch_1 variable is created by the TS compiler. You can find the Typescript code here https://github.com/tgamauf/onetimesecret-api/blob/1b8edff66bde11807c8ff7d29030b4d3e6661277/lib/request.ts#L150 and the compiled JS here https://github.com/tgamauf/onetimesecret-api/blob/1b8edff66bde11807c8ff7d29030b4d3e6661277/lib/request.js#L179.
As far as I can tell I am using the module as it is supposed to be used. What could cause this?
The ponyfill always fills even with native support if used via the jspm packager.
It looks like it's to do with the way that System wraps the module, an example of the ponyfill served to the browser is below:
(function(System, SystemJS) {(function (require, exports, module, __filename, __dirname, global, GLOBAL) {var __root__ = (function (root) {
function F() { this.fetch = false; }
F.prototype = root;
return new F();
})(typeof self !== 'undefined' ? self : this);
(function(self) {
(function(self) {
if (self.fetch) {
return
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob();
return true
------ SNIP ---------
self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = function() {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
};
self.fetch.polyfill = true;
})(typeof self !== 'undefined' ? self : this);
}).call(__root__, void(0));
var fetch = __root__.fetch;
var Response = fetch.Response = __root__.Response;
var Request = fetch.Request = __root__.Request;
var Headers = fetch.Headers = __root__.Headers;
if (typeof module === 'object' && module.exports) {
module.exports = fetch;
}
}).apply(__cjsWrapper.exports, __cjsWrapper.args);
})(System, System);```
https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md#v261
This is important security update.
Seems like cross-fetch
has a memory leak. Tested in the browser (Google Chrome, 88). The issue is reproduced by simple script (ignore CORS error, it behaves the same when request is resolved) which fires requests in interval:
setInterval(() => {
fetch('https://google.com')
.then(console.log, console.log)
}, 250)
After profiling around 1 minute, we can see that event listeners are constantly growing:
While they are fine with native fetch
:
I do understand that mabe it's not the purpose of this lib (feel free to close in case).
But would be useful adding a dns cache layer.
It's one of the common problem nowadays with huge number of requests using node-fetch
. It doesn't cache anything.
Or maybe it's worth just mentioning this in Readme.
TypeError: realFetch.call is not a function
at fetch (/usr/lib/leaguegamer/webserver/build/webpack:/datalibrary/node_modules/cross-fetch/dist/node-ponyfill.js:9:1)
When I inspect the import using the developer tools, the realFetch is an object, and not a function. On this object, there is the fetch function.
I'm unsure if this is a problem with the library or some kind of weird artifact that I have with the build. It would seem to be the latter, but I can't track it down. Any idea why require('node-fetch') is returning an object?
Access to XMLHttpRequest at 'http://easy-mock.com/mock/api/banner' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
env:
create-react-app: 2.2.1
Since index.d.ts contains /// <reference lib="dom" />
, all the lib.dom types are imported globally for anyone who uses cross-fetch: microsoft/TypeScript#33901
That means if I'm working in a TypeScript project where I don't want to have lib.dom available (which is surely true of anyone using cross-fetch) I have to somehow override the cross-fetch typings.
I suggest depending on @types/node-fetch
instead and using
export * from 'node-fetch';
export { default } from 'node-fetch';
to re-export the declarations from it.
It is working on desktop and latest android phone. But when i test on followings, it is not working
Chrome 78.0.3904.108
Android 4.4.2 H60-L04 Build/HDH60-L04
Agent:Mozilla/5.0 (Linux; Android 4.4.2; H60-L04 Build/HDH60-L04) Apple WebKit/537.36 (KHTML, like Gecko) version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.