简体   繁体   English

Angular:在发布请求时获得 Http 400 错误请求

[英]Angular :getting Http 400 bad request on post request

I have a form as follows我有一个表格如下

<form #demoForm = "ngForm" (ngSubmit) = "onClickSubmit(demoForm.value)" >
        <input type = "text" name ="fruit" id="add" placeholder = "Enter fruit name" ngModel>
        <input type = "submit" value = "add">
</form>

and following method gets invoked on form submission并在表单提交时调用以下方法

onClickSubmit(data) {
  alert("Entered Fruitname : " + data.fruit);
  console.log(data);
  this.ob = this.http.post("http://localhost:8080/demo/add", data).subscribe();

}

It logs {fruit: "apple"} in console on form submission with input value apple however I'm getting http 400 bad request on form submission.它在表单提交时在控制台中记录{fruit: "apple"}输入值 apple 但是我在表单提交时收到了 http 400 错误请求。 Error I'm getting is我得到的错误是

error: "Bad Request"
message: "Required String parameter 'fruit' is not present"
path: "/demo/add"
status: 400

Even though the object contains a fruit field as shown in the log, why is it still resulting in error即使对象包含日志中显示的水果字段,为什么仍然导致错误

Spring controller is弹簧控制器是

    @Controller 
    @CrossOrigin(origins="*")
    @RequestMapping(path="/demo")
    public class MainController {
      @Autowired
      private FruitsRepository fruitsRepository;

      @PostMapping(path="/add") 
      public void addNewUser(@RequestParam String fruit) {
          Fruits fruits=new Fruits();
          fruits.setName(fruit);
          fruitsRepository.save(fruits);
    }
}

how to solve this issue?如何解决这个问题?

You are sending the whole object, not only t he name.您正在发送整个对象,而不仅仅是名称。
{fruit: "apple"} is not a string, it is an object. {fruit: "apple"}不是字符串,而是一个对象。

To send only the fruit name (and so, a string), do the POST that way:要仅发送水果名称(以及字符串),请按以下方式执行 POST:

this.ob = this.http.post("http://localhost:8080/demo/add", data.fruit).subscribe();

@RequestParam String fruit expects a query parameter, not a value inside the request body. @RequestParam String fruit需要一个查询参数,而不是请求正文中的值。 Ie a request with the path http://localhost:8080/demo/add?fruit=apple , not {"fruit": "apple"} posted to http://localhost:8080/demo/add .即带有路径http://localhost:8080/demo/add?fruit=apple的请求,而不是{"fruit": "apple"}发布到http://localhost:8080/demo/add

define data of which type定义哪种类型的数据

     onClickSubmit({data}: {data}) {
       alert("Entered Fruitname : " + data.fruit);
       console.log( data);
       this.ob = this.http.post("http://localhost:8080/demo/add", data.fruit).subscribe();

     }

and backend is expecting only a string of variable name as fruit soo send only fruit variable后端只需要一串变量名作为fruit soo只发送fruit变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM