必需的字符串参数'name'不存在



我收到标题中命名的错误。

不知道发生了什么

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

在春季启动中:

@RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String getFoos(@RequestParam String name) {
        System.out.println("Received POST request:" + name);
        return null;
    }

前端

在这里,您作为附加到 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;
    }

注意:如果您使用的是@RestController,则无需使用@ResponseBody

如果您想发送多个数据,那么理想的方法是在后端创建一个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();
    }

如果您不想更改前端代码,可以将后端代码从 @RequestParam 更改为 @RequestBody,因为您不是在前端添加参数而是添加主体。

客户端在请求正文中传递"name",但服务器期望"name"作为请求参数。

要将"名称"作为请求参数传递,您可以尝试:

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();

最新更新