我有一个奇怪的情况,可能是因为我错过了一些我没有意识到或不知道的事情。 我正在使用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的第二个参数似乎不起作用?
在此先感谢您的答复或反馈。
答案 0 :(得分:2)
您正在使用两个强制性参数定义端点URL,并且这些参数必须在URL中(请选中here),因此,当您向端点发出请求时,URL必须为:
http://localhost:8080/logon?userID=yourUserId&password=yourUserPassword
在第一个实现中,您没有将查询参数添加到url中,因此请求发送到url http://localhost:8080/logon/ ,因为它没有必需的参数,即您的网络层返回400 http code,表示请求错误(再次,您的网址不包含必需的参数)。
答案 1 :(得分:0)
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) ) }