【问题标题】:Access to fetch at 'https://randomuser.me/api/?results=4' from origin 'http://localhost:3000' has been blocked by CORS policy:CORS 策略已阻止从源“http://localhost:3000”访问“https://randomuser.me/api/?results=4”获取:
【发布时间】:2020-09-17 05:39:39
【问题描述】:

我在控制台中不断收到此问题,但我不明白,请有人帮我解释一下。 CORS 策略已阻止从源“http://localhost:3000”获取“https://randomuser.me/api/?results=4”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

【问题讨论】:

  • 您提出什么要求?一个简单的 GET 不需要任何 CORS 处理。给minimal reproducible examplefetch('https://randomuser.me/api/?results=4').then((res) => res.json()).then((body) => console.log(body)) 在我的浏览器中按预期工作。

标签: javascript reactjs


【解决方案1】:

为了能够在 react 应用程序中允许 API 代理 - 您需要使用以下内容编辑 package.json

"proxy": "https://randomuser.me",

更多细节可以在 create-react-dev docs找到

【讨论】:

  • 非常感谢我终于使用了这个。
【解决方案2】:

在您的 api 域 https://randomuser.me 中,将 localhost 添加到您的允许来源列表中。

您收到此错误的原因是因为https://randomuser.me 期望来自https://randomuser.me 的请求,而不是来自您的localhost 等其他来源的请求。如果不满足此要求,浏览器会将其作为警告/错误返回。

【讨论】:

  • 非常感谢。
猜你喜欢
  • 2020-07-29
  • 2021-01-24
  • 2021-03-08
  • 2021-07-03
  • 2020-11-11
  • 1970-01-01
  • 2021-01-23
  • 2019-04-11
  • 2021-10-05
相关资源
最近更新 更多