必需的字符串参数“名称”不存在

时间:2019-07-11 07:59:12

标签: spring-boot react-native post

我得到标题中标明的错误。

不确定发生了什么

在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;
    }

3 个答案:

答案 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();
    }