Spring post方法“缺少所需的请求正文”

Ion*_*nut 7 rest post spring spring-boot

@PostMapping(path="/login")
public ResponseEntity<User> loginUser(@RequestBody Map<String, String> userData) throws Exception {
    return ResponseEntity.ok(userService.login(userData));
}
Run Code Online (Sandbox Code Playgroud)

我在 UserController 中有这个登录方法。问题是当我尝试为登录发出 post 请求时,我收到此错误:

{
"timestamp": "2018-10-24T16:47:04.691+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request body is missing: public org.springframework.http.ResponseEntity<org.scd.model.User> org.scd.controller.UserController.loginUser(java.util.Map<java.lang.String, java.lang.String>) throws java.lang.Exception",
"path": "/users/login"
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

cos*_*mos 15

如果是 POST 请求,则必须将其作为 JSON 传递到正文中。

在此处输入图片说明


Flo*_*n D 15

我遇到了类似的问题,在我的 Spring Boot 服务中遇到此错误

HttpMessageNotReadableException:缺少必需的请求正文:...

我的问题是,当我从Postman发出请求时,“Content-Length”标头未选中,因此服务不考虑请求正文。


小智 9

This is happening because you are not passing a body to you server. As can I see in your screenshot you are passing email and password as a ResquestParam.

To handle this values, you can do the following:

@PostMapping(path="/login")
public ResponseEntity<User> loginUser(@RequestParam("email") String email, @RequestParam("password") String password) {
     //your imp
}
Run Code Online (Sandbox Code Playgroud)

In order to accept an empty body you can use the required param in the RequestBody annotation:

@RequestBody(required = false)
Run Code Online (Sandbox Code Playgroud)

But this will not solve your problem. Receiving as RequestParam will.

If you want to use RequestBody you should pass the email and password in the body.