【问题标题】:Access to fetch at 'http://localhost:8080/demo/getAll' from origin 'http://localhost:3000' has been blocked by CORS policyCORS 策略已阻止从源“http://localhost:3000”访问“http://localhost:8080/demo/getAll”获取
【发布时间】:2021-07-03 17:09:00
【问题描述】:

我用 Spring 构建了一个后端,现在我想用 React 构建一个前端。当我尝试获取我的请求 URL 时,我收到以下错误:

CORS 策略已阻止从源“http://localhost:3000”获取“http://localhost:8080/demo/getAll”的访问权限:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

这是我的代码:

const fetchItems = async () => {
fetch('http://localhost:8080/demo/getAll').then(response => response.json()).then(data => 
console.log(data));
};

有谁知道问题出在哪里,我该如何解决?

【问题讨论】:

    标签: reactjs spring cors postman


    【解决方案1】:

    https://www.w3.org/Security/wiki/Same_Origin_Policy

    来源由 URL 的方案、主机和端口定义

    端口必须与过去相同的来源相同。

    对于 react,你有它的代理,所以你向 :3000 发出请求,它会像你发送到 :8080 一样行事

    如果您使用 Create React App,这很容易完成:https://create-react-app.dev/docs/proxying-api-requests-in-development/

    否则,您最好的选择可能是修改后端的 CORS 标头:How does Access-Control-Allow-Origin header work?

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2021-01-20
      • 2020-07-29
      • 2021-01-24
      • 2022-11-04
      • 2021-03-08
      • 1970-01-01
      • 2021-01-23
      • 2020-12-27
      相关资源
      最近更新 更多