简体   繁体   English

Angular调用Java Web API中的http.post传递参数

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

I have a weird situation that may be because I missed something that I didn't realized or know. 我有一个奇怪的情况,可能是因为我错过了一些我没有意识到或不知道的事情。 I am creating a simple login UI using Angular and call the Web API created in java. 我正在使用Angular创建一个简单的登录UI,并调用用Java创建的Web API。

The java web API function is as follows 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)

Now if I use the http.post as follows 现在,如果我按如下方式使用http.post

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

Then I get the following error in the Google Chrome browser: 然后,我在Google Chrome浏览器中收到以下错误:

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

But if I change the code as follows: 但是,如果我将代码更改如下:

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

It work perfectly. 完美运作。 Am I missing something? 我想念什么吗? Why the second parameter of http.post that should be the parameter passed not seems to be working? 为什么应该传递的参数http.post的第二个参数似乎不起作用?

Thanks in advance for any reply or feedback. 在此先感谢您的任何答复或反馈。

You are defining your endpoint url with two mandatory parameters, and such parameters must be in the url (check here ), so when you make a request to your endpoint, the url must be : 您正在使用两个强制性参数定义端点url,并且这些参数必须在url中(请在此处检查),因此在向端点发出请求时,该URL必须为:

http://localhost:8080/logon?userID=yourUserId&password=yourUserPassword HTTP://本地主机:8080 /登录用户ID = yourUserId和密码= yourUserPassword

In the first implementation you are not adding the query parameters to the url so the request is made to the url http://localhost:8080/logon/ as it doesn't have the required parameters, your web tier is returning the 400 http code , which implies a bad request (because again, your url doesn't contains the required parameters). 在第一个实现中,您没有将查询参数添加到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