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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52974330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:46:41  来源:igfitidea点击:

Spring post method "Required request body is missing"

springrestspring-bootpost

提问by Ionut

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

I have this method for the login in the UserController. The problem is when i try to make the post request for the login i get this error:

我在 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"
}


enter image description here

在此处输入图片说明

回答by L. Figueredo

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.

发生这种情况是因为您没有将正文传递给您的服务器。正如我在您的屏幕截图中看到的,您将电子邮件和密码作为 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
}

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

为了接受空正文,您可以使用requiredRequestBody 注释中的参数:

@RequestBody(required = false)

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

但这并不能解决您的问题。像 RequestParam 一样接收。

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

如果你想使用 RequestBody 你应该在body 中传递电子邮件和密码。

回答by cosmos

You have to pass that as JSON in your body, if it's a POST request.

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

enter image description here

在此处输入图片说明

回答by user7294900

You need to send data in Body as JSON

您需要将 Body 中的数据作为 JSON 发送

 { "email":"[email protected]", "password":"tuffCookie"}