簡體   English   中英

Angular調用Java Web API中的http.post傳遞參數

[英]parameter passing for http.post in Angular calling java web API

我有一個奇怪的情況,可能是因為我錯過了一些我沒有意識到或不知道的事情。 我正在使用Angular創建一個簡單的登錄UI,並調用用Java創建的Web API。

Java Web API函數如下

@RequestMapping(value = "/logon", method = RequestMethod.POST, produces = {"application/json"})
@ResponseBody
public String logon(
        @RequestParam(value = "userID", required = true) String userID,
        @RequestParam(value = "password", required = true) String password,
        HttpServletRequest request)

現在,如果我按如下方式使用http.post

login(username: string, password: string) {
    return this.http.post(this.url+"/security/logon/", 
                          JSON.stringify({ userID: username, password: password }) )

然后,我在Google Chrome瀏覽器中收到以下錯誤:

POST http://localhost:8080/logon/ 400 (Required String parameter 'userID' is not present)

但是,如果我將代碼更改如下:

login(username: string, password: string) {
    var usrpwd = "userID=" + username + "&password=" + password;
    return this.http.post(this.url+"/security/logon?"+usrpwd, usrpwd )

完美運作。 我想念什么嗎? 為什么應該傳遞的參數http.post的第二個參數似乎不起作用?

在此先感謝您的任何答復或反饋。

您正在使用兩個強制性參數定義端點url,並且這些參數必須在url中(請在此處檢查),因此在向端點發出請求時,該URL必須為:

HTTP://本地主機:8080 /登錄用戶ID = yourUserId和密碼= yourUserPassword

在第一個實現中,您沒有將查詢參數添加到url中,因此請求發送到url http:// localhost:8080 / logon /,因為它沒有必需的參數,您的Web層返回了400 http code ,表示請求錯誤(再次,您的url不包含必需的參數)。

constructor(private http:HttpClient){

}

login(usrName,usrPwd){

let body = {userName:usrName, userPwd:usrPwd}; this.http.post("http://localhost:5000/security/login", body) .subscribe( res => console.log(res), error => console.log(error) ) }

暫無
暫無

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

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