我遇到了一个奇怪的情况,可能是因为我错过了一些我没有意识到或不知道的事情。 我正在使用 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 中(检查 here ),因此当您向端点发出请求时,URL 必须为:
http://localhost:8080/logon?userID=yourUserId&password=yourUserPassword
在第一个实现中,您没有将查询参数添加到 url,因此请求是向 url http://localhost:8080/logon/ 发出的。 因为它没有所需的参数,所以您的 Web 层返回 400 http code ,这意味着一个错误的请求(因为您的 url 不包含所需的参数)。
关于java - Angular 调用 java web API 中 http.post 的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52306198/