首页 > 解决方案 > Spring Boot Java 发布请求

问题描述

我正在尝试从 React(客户端)到 Java 服务器端进行简单的发布请求。下面是我的控制器。

package com.va.med.dashboard.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.va.med.dashboard.services.VistaServiceImpl;
import gov.va.med.exception.FoundationsException;

@RestController
@RequestMapping("/dashboard")
public class DashboardController  {

   @Autowired
   private VistaServiceImpl vistaService;

   @RequestMapping("/main")
   String home() {
          return "main route";
   }

   @RequestMapping("/rpc")
   String test() throws FoundationsException {
          vistaService.myAuth();
          return "this is rpc route";
   }

   @RequestMapping(method = RequestMethod.POST, produces = 
"application/json", value = "/vista")
   @ResponseStatus(value = HttpStatus.ACCEPTED)
   public String getVistaConnection(@RequestBody String ipString, @RequestBody String portString, @RequestBody String accessPin,
   @RequestBody String verifyPin) {

       System.out.println(ipString);
       System.out.println(portString);
       System.out.println(accessPin);
       System.out.println(verifyPin);

       vistaService.connect(ipString, portString, accessPin, verifyPin); // TO-DO populate with serialized vars
       if (vistaService.connected) {
              return "Connected";
       } else {
              return "Not Connected";
       }
   }
}

以下是我的反应 axios 发布请求

 axios.post('/dashboard/vista', {
  ipString: this.state.ipString,
  portString: this.state.portString,
  accessPin: this.state.accessPin,
  verifyPin: this.state.verifyPin
})
.then(function (response){
  console.log(response);
})
.catch(function (error){
  console.log(error);
});    

这也是我得到的错误。

Failed to read HTTP message:     
org.springframework.http.converter.HttpMessageNotReadableException: 
Required request body is missing:

谁能解释一下这个错误信息?我来自纯 JavaScript 背景,所以对于 Java 有很多我不知道的事情,因为它是在 JavaScrips 语言中自动实现的。

再次提前感谢!

标签: javareactjshttpspring-boot

解决方案


你这样做是错的。

代替

public String getVistaConnection(@RequestBody String ipString, @RequestBody String portString, @RequestBody String accessPin,RequestBody String verifyPin)

您应该将这些参数包装在一个类中:

public class YourRequestClass {
   private String ipString;
   private String portString;
   ....
   // Getter/setters here
}

您的控制器方法将如下所示:

public String getVistaConnection(@RequestBody YourRequestClass request)

来自@Rajmani Arya:

由于 RestContoller 并@RequestBody假设读取 JSON 正文,因此在您的axios.post通话中您应该放置标题Content-Type: application/json


推荐阅读