如何从Angle App向Spring发送发帖请求?

时间:2020-03-13 18:35:10

标签: java angular spring spring-boot post

我正在尝试使用用户名和密码发送端口请求:

signUp(username, password): Observable<String> {
return this.http.post<String>("http://localhost:8080/signUp", {
  params: { username: username, password: password }
});
}

对于具有此方法的spring服务:

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value="/signUp", method=RequestMethod.POST)
public ResponseEntity<String> signUp(@RequestParam ("username") String username, @RequestParam("password")  String password) throws IOException {
 //not important
 return new ResponseEntity<String>("Added successfully.", HttpStatus.OK);
}

当我发送它时,出现角度400错误。在春季服务中,我看到以下消息:

2020-03-13 19:32:38.486 WARN 13200 --- [nio-8080-exec-3] .wsmsDefaultHandlerExceptionResolver:已解决[org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数'username'是不存在]

我知道在该http请求中有从Angular应用程序发送的值(我检查了硬编码)。有人可以帮我解决吗?预先感谢。

2 个答案:

答案 0 :(得分:2)

@RequestBody@RequestParam之间似乎有些混乱-它们是两件事完全不同。

@RequestBody表示API期望请求有效载荷

@RequestParam希望将一个或多个参数传递给API 调用时的网址。

现在,后端希望在调用 request 参数时将其传入。例如:/signUp/username=abc,因此您需要从用户界面中传入此键值对,即

http.post<String>(`http://localhost:8080/signUp?username=${username}&password=${password}`)

400错误的请求是在您传递请求正文而不是 request参数时发出的。另一种解决方案是更改后端以接受请求有效负载-然后,您需要使用@RequestBody

答案 1 :(得分:0)

可能的解决方案可能是以下请求:

signUp(username, password): Observable<String> {
    return this.http.post<String>("http://localhost:8080/signUp", {
          username: username, password: password
    });
}

...在后端具有请求正文的类:

public class SignUp {
    private String username;
    private String password;
    // constructor, getters and setters or lombok @Data
}

...然后在您的控制器中:

@RequestMapping(value="/signUp", method=RequestMethod.POST)
public ResponseEntity<String> signUp(@RequestBody SignUp signUp) {
    // signUp.getUsername()...
    return new ResponseEntity<String>("Added successfully.", HttpStatus.OK);
}
相关问题