spring-boot - CORS 策略已阻止访问 fetch。它没有 HTTP ok 状态
问题描述
所以我正在构建一个反应应用程序,它从我构建的 spring boot rest api 中获取 JSON 数据。
下面是 fetch 方法的代码:
componentDidMount() {
fetch(`http://localhost:8080/students`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((data) => this.setState({students: data}));
console.log(this.state.students);
}
但是,当我运行该程序时,它给了我一个错误消息:
Access to fetch at 'http://localhost:8080/students' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
谁能帮我?
解决方案
我对 Spring Boot 不是 100% 熟悉,但这个问题的一般解决方案是确保您的服务响应与源匹配的 Access-Control-Allow-Origin 标头(在您的示例中为 localhost),如果它不是与您的服务相同的来源。
添加"Access-Control-Allow-Origin": "*"
会为您的开发目的而做。在生产中,您可能希望更具体地说明实际允许的来源。
查看此资源以获取有关 CORS 的更多信息:https ://enable-cors.org/
这是在您的浏览器中实施的相同来源策略导致了这种情况。它指定浏览器应该允许一个网页中的脚本访问另一个网页上的资源,但前提是它们来自同一来源。如果它们不是,您可以通过指定我上面提到的标头来指定它们是允许的。您可能还需要指定允许的动词和标题,具体取决于您在做什么。
推荐阅读
- python - 使用 python 和 beautifulsoup 获取联系信息
- rust - 如果条目已经存在,如何避免使用 HashMap entry/or_insert 习惯用法移动键?
- java - 带有 Long 类型键的 spring data redis zadd 不起作用
- android - 在 OpenGL Android 中加载更多较小的纹理与加载少量大纹理
- python - 熊猫不使用线性回归
- typescript - 如何在打字稿中对对象上的项目进行分组和计数?
- applescript - 在密码保护文件夹时陷入循环
- android - 运行所有协程类测试失败
- python - 错误:ValueError:应定义“密集”输入的最后一个维度。找到`无`
- geospatial - 使用 Dask 处理大型网格会导致 MemoryError