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
Spring post method "Required request body is missing"
提问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"
}
回答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 required
param in the RequestBody annotation:
为了接受空正文,您可以使用required
RequestBody 注释中的参数:
@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
回答by user7294900
You need to send data in Body as JSON
您需要将 Body 中的数据作为 JSON 发送
{ "email":"[email protected]", "password":"tuffCookie"}