gpt4 book ai didi

node.js - Fetch API 无法在 Electron 中加载

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:53 25 4
gpt4 key购买 nike

我有一个通过 React CLI 设置的 Electron 应用程序。它似乎工作正常,但是当我尝试执行外部 HTTP 请求时:

https.get('https://blockchain.info/q/24hrprice', (result) => {
console.log('RATE: ', result);
});

我得到:

Fetch API cannot load https://blockchain.info/q/24hrprice. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
If an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

最佳答案

您正在发出跨源请求(您的请求域与 API 的域不同),浏览器对此有特殊规则。在 Node 上下文中(即通过 Node 的 http/https 模块),您不必担心 CORS,并且通常可以对网络请求执行较低级别的工作。另一方面,浏览器围绕 CORS 具有很多安全性。当您使用 fetch 时,您的网络请求将通过 Chromium 的网络层,因此它受到这些限制。当您使用 Node 的 http/https 时,您正在使用 Node 的。这是 Electron 的一个令人困惑的地方——渲染器进程看起来像一个普通的 Web 上下文,但实际上你也可以访问所有 Node.js 的 API,允许你做一些在普通浏览器中无法做的事情。

我会检查并查看在该请求中包含 API key 是否会更改 API 的响应(可能会触发其 API 添加适当的 CORS header ,例如 Access-Control-Allow-Origin)。也许 API 并不意味着在浏览器上下文中调用,因此更面向 Node.js 的方法才是正确的选择。

这是一篇关于 CORS 及其处理方法的精彩文章:https://medium.com/@baphemot/understanding-cors-18ad6b478e2b

关于node.js - Fetch API 无法在 Electron 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com