我得到标题中标明的错误。
不确定发生了什么
在React Native中:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "http://[my ip address]:8000/add");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({name: this.state.name}));
在Spring Boot中:
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String getFoos(@RequestParam String name) {
System.out.println("Received POST request:" + name);
return null;
}
答案 0 :(得分:0)
如果您不想更改前端代码,则可以将后端代码从@RequestParam
更改为@RequestBody
,因为您不是在前端添加参数,而是在正文中添加代码。
答案 1 :(得分:0)
客户端在请求正文中传递“名称”,但是服务器希望“名称”作为请求参数。
要将“名称”作为请求参数传递,您可以尝试以下方法:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "http://[my ip address]:8000/add?name="+ this.state.name);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
答案 2 :(得分:0)
前端
您在此处以附加到URL的Path变量的形式进行请求。
http://[my ip address]:8000/add/stateName
。
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "http://[my ip address]:8000/add?name="+ this.state.name);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
后端
@RequestMapping(value = "/add/{name}", method = RequestMethod.POST)
@ResponseBody
public String getFoos(@PathVariable(name="name") String name) {
System.out.println("Received POST request:" + name);
return name;
}
注意:如果您使用的是@ResponseBody
@RestController
如果要按以下方式发送多个数据,那么理想的方法是在后端创建一个 DAO / DTO
const booking = {
name: this.state.name,
location: this.state.location,
pax: this.state.pax,
};
后端
public class StateDto{
private String name;
private String location;
private String pax;
//Getter-Setters, AllArgConstructor-SuperConstructor
}
那么您的控制器将如下所示
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String getFoos(@RequestBody StateDto stateDto) {
System.out.println("Received POST request:" + stateDto.getName());
return stateDto.getName();
}