【问题标题】:Spring Controller GET/POST/PUT to another interfaceSpring Controller GET/POST/PUT 到另一个接口
【发布时间】:2022-02-04 11:06:35
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: java reactjs spring spring-boot spring-mvc


    【解决方案1】:

    据我了解,您希望使用 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 注释设置为 set 。

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      相关资源
      最近更新 更多