Spring控制器GET/POST/PUT到另一个界面

Spring Controller GET/POST/PUT to another interface

我使用 React 作为前端,Java Spring Boot 作为后端。 React 将 JSON 表单数据作为 GET/PUT/POST 请求发送到我的后端 url (http://localhost:8080/test)。现在,我不想将此 JSON 转发到另一个接口 GET 端点 (https:///another/interface/add?id={id})。该接口然后根据 id 查询数据库并回答 200 OK 消息以及我需要显示的 JSON 回复(发送回前端)。

1. 从 Spring 引导后端向另一个接口发送请求的正确方法是什么?我用同样的方法捕获了前端数据?
2. 我还必须将 HTTP headers 设置为 GET 请求,我将如何处理?

前端如何将 id 字段作为 JSON 发送到后端的示例:
反应 POST

    addId = async (data) => {
        return this.post(/localhost:8080/test/id, data)
    }

后端如何接收 id 字段的示例:
Spring开机POST

    @PostMapping("test/id")
    public String test(@RequestBody String id) {
        return id;
    }

据我了解,您想使用 json body 和 httpstatuscode 200 从后端获取数据。我说的对吗?

也许你可以试试这个

@GetMapping(/interface/add)
public ResponseEntity<?> test(@RequestParam("id") String id){
  //write code you want
return ResponseEntity.status(HttpStatus.OK).body("string" or dto possible);
}

ResponseEntity 发送带有 httpstatus 代码的正文,如果你想发送 requestparam,你设置 @RequestParam 注释来设置 .

  1. 当我用 springboot 做项目并做出反应时。我使用 json 类型来交换数据。大多数服务通常使用 json 数据类型交换数据。

2.I 对这个问题感到困惑 如果你将数据 React 发送到 springboot 你的代码是正确的 Axios.get("localhost....", data) 您可以更改 http 类型 Axios.(get, post, delete)