【问题标题】:Spring method with React front带有 React 前端的 Spring 方法
【发布时间】: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”来获取,但它并没有改变任何东西。谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: reactjs spring fetch


    【解决方案1】:

    cors origin 中的斜杠导致错误。

    @CrossOrigin(origins = "http://localhost:3000") // no slash at end in origin.
    

    希望这能解决您的问题。

    【讨论】:

    • 也许我不应该承认,但我整个晚上都在为此苦苦挣扎。非常感谢。 :D
    猜你喜欢
    • 2017-03-04
    • 2021-09-17
    • 2014-04-12
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多