【问题标题】:How to send post request from angular app to spring?如何将帖子请求从角度应用程序发送到弹簧?
【发布时间】:2020-03-13 18:35:10
【问题描述】:

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

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);
}

当我发送它时,我收到 http 400 错误。在春季服务中,我看到此消息:

2020-03-13 19:32:38.486 WARN 13200 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数“用户名”是不存在]

我知道在那个 http 请求中有从 Angular 应用程序发送的值(我用硬编码检查过)。有人可以帮我解决吗?提前致谢。

【问题讨论】:

  • 您是否尝试过在“参数”对象之外传递用户名和密码?
  • 似乎您发送的是请求正文而不是请求参数,但您的后端期望后者。
  • 您的请求负载是{"params":{"username":"test","password":"test"}},这不是后端所期望的。

标签: java angular spring spring-boot post


【解决方案1】:

@RequestBody@RequestParam 之间似乎有些混淆——它们是完全不同的两个东西。

@RequestBody 表示 API 需要一个请求负载

@RequestParam 期望将一个或多个参数传递给 API 调用时的url。

现在,后端期望在调用时传入一个 request 参数。例如:/signUp/username=abc,因此您需要从 UI 中传入此键值对,即

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

400 错误请求源于您传入 请求正文 而不是 请求参数。另一种解决方案是更改后端以接受请求负载 - 然后您需要使用 @RequestBody

【讨论】:

    【解决方案2】:

    一个可能的解决方案可能是这个请求:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2018-11-12
      • 1970-01-01
      • 2014-02-19
      • 2016-11-08
      • 2018-05-25
      • 1970-01-01
      相关资源
      最近更新 更多