【问题标题】:How to Set Up a RESTful API with Spring如何使用 Spring 设置 RESTful API
【发布时间】:2026-02-05 21:30:01
【问题描述】:

我正在尝试使用 Spring 设置一个 RESTful API,将 react 用于前端。客户端要发送一个类似这样的 POST 请求:

{
   "previousDecisions": [0, 1, 2]
}

然后服务器将响应一个名为 Node 的对象,它在转换为 JSON 后如下所示:

{
  "id": 0,
  "text": "Something here...",
  "decisions": [],
  "children": [],
  "speaker": 0,
  "checkpoint": true
}

我正在努力遵循我看到的一些示例代码,以了解如何使用 Spring 进行设置。

后端的设置方式是:

有一个Decide 类、一个Node 类和一个DecideController 类。 DecideController 应该像上面那样接受一个 POST 请求,然后使用 Decide 类获取 Node 类的实例并将其用作对客户端的响应。

我还没有开始测试客户端,但我正在使用 Intellij Restful API 工具来检查它是否正常工作并且它给了我一个错误。以下是我应该处理 POST 请求的实际方法:

@RestController
public class DecideController {

  @PostMapping("/decide")
  public Node decide(@Valid @RequestBody Decide decide) {
    return decide.getNode();
  }
}

当我使用此正文发送请求时收到错误响应:

{
   "previousDecisions": [0, 1, 2]
}

还有这些标题:

Accept: application/json
Cache-Control: no-cache

这是错误响应:

{"timestamp":"2019-09-01T23:54:58.037+0000","status":500,"error":"Internal Server Error","message":"Content-Type cannot contain wildcard type '*'","path":"/decide"}

我能想到的最后一件事是您可能需要帮助我的是 Decide 类,它很短,所以我也将在此处包含它:

public class Decide {

  private int[] decisionList;

  public Decide(int[] decisionList) {
    this.decisionList = decisionList;
  }

  public Node getNode() {
    //Use the game class to get a root node for the entire story tree
    Node rootNode = (new Game()).getFullStoryTree();

    //Traverse the story tree using the decisionList to get to the current node
    Node currentNode = rootNode;
    for (int whichChild : this.decisionList) {
      currentNode = currentNode.getChild(whichChild);
    }

    return currentNode;
  }
}

如前所述,我对该 POST 请求的期望是如下所示的响应:

{
  "id": 0,
  "text": "Something here...",
  "decisions": [],
  "children": [],
  "speaker": 0,
  "checkpoint": true
}

抱歉,我对这一切都很陌生,所以希望我在这里所说的一切都有意义,但如果不是,我很乐意澄清或提供更多信息。谢谢!!

【问题讨论】:

  • 我相信错误消息说明了问题所在,是您的内容类型。不是吗?

标签: java spring rest http


【解决方案1】:

错误来自服务器,因为客户端:

"Internal Server Error","message":"Content-Type cannot contain wildcard type '*'"

即使 PAYLOAD 看起来没问题,您的反应客户端正在将 Content-Type HTTP 标头设置为“*”。你需要在 react 中解决问题。

建议: 按照这个link 将Content-Type 设置为application/json

【讨论】:

  • 感谢您,这是一个非常简单的解决方案。我对 HTTP 标头了解不多,所以我有一些研究要做。