繁体   English   中英

交叉获取不适用于React Native

[英]cross-fetch doesn't work with React Native

我已经编写了一个API包装器,该包装器使用访存来执行API请求。 当我打算使模块与Browsers,Node和React Native兼容时,我使用cross-fetch 现在,如果我使用Node对其进行测试,则它可以正常工作,但是如果在React Native中使用包装器,但失败并出现以下错误: TypeError: undefined is not a function (evaluating 'cross_fetch_1.default(url, init)') 如果打印出cross_fetch_1的类型,则会得到:

{ [Function]
  polyfill: true,
  Response: { [Function: Response] error: [Function], redirect: [Function] },
  Request: [Function: Request],
  Headers: [Function: Headers] }

对于cross_fetch_1.default或cross_fetch_1.fetch,则为“未定义”。

该库是使用Typescript开发的,因此cross_fetch_1变量是由TS编译器创建的。 您可以在这里找到打字稿代码https://github.com/tgamauf/onetimesecret-api/blob/1b8edff66bde11807c8ff7d29030b4d3e6661277/lib/request.ts#L150和已编译的JS在这里https://github.com/tgamauf/onetimesecret-api /blob/1b8edff66bde11807c8ff7d29030b4d3e6661277/lib/request.js#L179

据我所知,我正在使用应该使用的模块。 是什么原因造成的?

我还在这里打开了一个关于此的github问题: https : //github.com/lquixada/cross-fetch/issues/26

当您在React Native中导入cross-fetch时,React Native模块捆绑node_modules/cross-fetch/dist/browser-ponyfill.js根据node_modules/cross-fetch/package.jsonbrowser字段选择node_modules/cross-fetch/dist/browser-ponyfill.js 我相信这里已经配置好 并且node_modules/cross-fetch/dist/browser-ponyfill.js仅提供导出分配,而不提供默认导出:

if (typeof module === 'object' && module.exports) {
module.exports = fetch;
}

node_modules/cross-fetch/dist/node-ponyfill.js ,后者具有导出分配和默认导出:

module.exports = exports = fetch;
exports.fetch = fetch;
exports.Headers = nodeFetch.Headers;
exports.Request = nodeFetch.Request;
exports.Response = nodeFetch.Response;

// Needed for TypeScript.
exports.default = fetch;

在项目上启用esModuleInterop编译器选项将使TypeScript修补差异,并使用导出分配完成默认导入。 但是,由于node-ponyfill.js明确建议cross-fetch作者打算支持使用不带esModuleInterop TypeScript的esModuleInterop ,因此我想说他们应该修复browser-ponyfill.js在相同的情况下工作。 我看到您已经提出了问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM