【发布时间】:2020-09-16 16:17:14
【问题描述】:
您好,我正在尝试使用 React Front 和 Spring Java 后端创建小项目。 假设在 Spring Controller 类中我有一个方法:
@CrossOrigin(origins = "http://localhost:3000/")
@GetMapping("/something")
public void printSomething()
{
System.out.println("examplePhrase");
}
在 React 中,我有一个带有按钮的表单,它调用方法“handleSpring”看起来像:
handleSpring = e =>
{
e.preventDefault();
console.log("Method started");
const SpringAPI = `http://localhost:8080/something`
fetch(SpringAPI, {})
.then(response => console.log("method works"))
.catch(err => console.log("method failed"))
}
当我运行这两个应用程序并转到“localhost:8080/something”时,我在 Intellij 控制台“examplePhrase”中有一条消息,因此 Spring 方法有效。当我要去“localhost:3000”时,我的表单是由 React 制作的。但是当我右键单击该站点时,在浏览器菜单中选择“检查”->“控制台”,然后按表单按钮我有一个错误:
方法开始 localhost/:1 访问从源“http://localhost:3000”获取“http://localhost:8080/something”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。 App.js:50 GET http://localhost:8080/something net::ERR_FAILED App.js:50 方法失败
我尝试添加“no cors”来获取,但它并没有改变任何东西。谁能告诉我如何解决这个问题?
【问题讨论】: