gpt4 book ai didi

javascript - 如何摆脱 React.js 中的 NO ACCESS CONTROL ORIGIN 错误?

转载 作者:行者123 更新时间:2023-12-02 21:01:08 26 4
gpt4 key购买 nike

我正在尝试从使用 React.js 的 fetch 方法的 API 中获取数据。但我经常看到这个错误

Access to fetch at https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY} from origin http://localhost:3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我已禁用扩展等,但我想这需要在请求中添加一些额外的 header 等。请帮忙。

最佳答案

此问题与 React 无关,而是与 CORS 相关。来自 documentation

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

这是一个需要在服务器端修复的问题。需要添加的不是 header 中的请求,而是响应中的请求。具体来说,需要添加Access-Control-Allow-Origin

要了解 CORS 存在的原因,请假设我创建了一个可以代表您向 Gmail 发出网络请求的网站。这使我能够阅读您的电子邮件。浏览器会阻止这种情况,因此只有 Gmail 可以读取 Gmail。

您的问题可能有其他解决方案,具体取决于您尝试与哪个 API 通信、您的设置是什么以及您有哪些限制。如果您使用create-react-app ,一个快速解决方法可能是将其添加到您的 package.json 中:

"proxy": "https://api.edamam.com",

现在删除https://api.edamam.com来自您的 fetch 调用。所以而不是 fetch('https://api.edamam.com/path/to/server') ,你需要做fetch('/path/to/server') ,注意需要重启开发服务器。您可以阅读有关其工作原理的更多信息 here

关于javascript - 如何摆脱 React.js 中的 NO ACCESS CONTROL ORIGIN 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61353630/

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