java - 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 语言中自动实现的。
再次提前感谢!
解决方案
你这样做是错的。
代替
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
推荐阅读
- laravel - 计算具有相同地址的用户并将其返回到刀片视图中
- ios - 无法在模拟器上打开并运行我的 .xcworkspace 项目
- javascript - javascript从反向查找字符串中的字符
- flutter - 如何自动导入 FLUTTER 包 Visual Studio Code ver: 1.51.1 Windows 10
- ruby - Azure ruby sdk 存储帐户创建参数,没有方法allow_blob_public_access
- dynamics-crm - 表单从 Web 资源附加了事件处理程序
- postgresql - 数据工厂Postgres查询日期时间错误
- python - 如何编写一个返回 numpy 数组的 sagemaker tensorflow input_handler()?
- javascript - for循环后的“if(td)”解释
- python - 如何使用 Dual Bay Docking Station 在 python 中获取硬盘序列号?