reactjs - 带有 React 前端的 Spring 方法
问题描述
嗨,我正在尝试使用 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”来获取,但它并没有改变任何东西。谁能告诉我如何解决这个问题?
解决方案
cors origin 中的斜杠导致错误。
@CrossOrigin(origins = "http://localhost:3000") // no slash at end in origin.
希望这可以解决您的问题。
推荐阅读
- java - 如何在调用意图活动后修复应用程序崩溃
- c# - Youtube 直播 API - 列出观看用户
- json - 在 Azure 中处理 JSON
- c# - 在数据库中搜索选定的选中列表框项
- node.js - TypeError:util.Long.fromValue 不是函数 - stackdriver
- excel - 如果在另一张纸上找不到,则复制单元格
- openlayers - Openlayers-5 WFS-T: formatGML with srsName:'EPSG:4326'
- javascript - 如何在 vuejs 中将“.find()”与数组一起使用
- typescript - vscode IntelliSense 无法与打字稿中的重载函数正常工作
- angular - 离子网格无法在 ionic 3 中渲染