我正在尝试从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 post请求
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背景,所以很多我不熟悉的东西,因为它是在JavaScrips语言中自动实现的。
提前再次感谢!
答案 0 :(得分:3)
你做错了。
而不是
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
答案 1 :(得分:0)
尝试用@RequestParam
替换所有@RequestBody注释public String getVistaConnection(@RequestParam String ipString, @RequestParam String portString, @RequestParam String accessPin, @RequestParam String verifyPin)