簡體   English   中英

如何從 angular 應用程序向 spring 發送發布請求?

[英]How to send post request from angular app to spring?

我正在嘗試使用用戶名和密碼發送端口請求:

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

當我發送它時,在 angular 中我收到 http 400 錯誤。 在春季服務中,我看到此消息:

2020-03-13 19:32:38.486 WARN 13200 --- [nio-8080-exec-3] .wsmsDefaultHandlerExceptionResolver:已解決 [org.springframework.web.bind.MissingServletRequestParameterException:所需的字符串參數“用戶名”不存在]

我知道在那個 http 請求中有從 Angular 應用程序發送的值(我用硬編碼檢查過)。 有人可以幫我解決嗎? 提前致謝。

似乎@RequestBody@RequestParam之間存在混淆——它們是兩個完全不同的東西。

@RequestBody 表示 API 需要一個請求負載

@RequestParam 期望在調用時將一個或多個參數傳遞給 API url。

現在,后端期望在調用時傳入一個請求參數。 例如: /signUp/username=abc ,因此您需要從 UI 傳入此鍵值對,即

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

400 錯誤請求源於您傳入請求正文而不是請求參數 另一種解決方案是更改后端以接受請求有效負載 - 然后您需要使用@RequestBody

一個可能的解決方案可能是這個請求:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM