繁体   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