首页 > 解决方案 > 如何将spring POST API的@RequestParams定义为Angular的Http post方法?

问题描述

我有一个 REST API,它接受两个参数,即用户名和密码,并根据前端的用户输入将结果设为真或假。我在将 REST API 调用到我的 Angular 8 代码时遇到了一些问题。

春季休息API

@RequestMapping(value = "/checkData", method = RequestMethod.POST)
public String Authentication(@RequestParam("username") String username, @RequestParam("password") String password) {

}

我正在尝试通过我的 Angular 8 应用程序通过服务访问给定的 API,并将服务定义如下:

AuthLoginInfo.ts

export class AuthLoginInfo {
    username: string;
    password: string;
 
    constructor(username: string, password: string) {
        this.username = username;
        this.password = password;
    }
}
checkLogin(userInfo : AuthLoginInfo){
     return this.http.post(`${API_URL}/APP/checkData/${userInfo.username}/
       ${userInfo.password}`,{},{responseType: 'text'})
  }

但是当我运行我的应用程序时,我没有得到正确格式的参数。谁能告诉我如何在 HTTP POST API 中定义请求参数?

预先感谢您的建议。

标签: springspring-bootpostangular8spring-rest

解决方案


从前端发送它们的方式,它们被视为路径参数而不是查询参数。以相同的方式配置您的后端

@RequestMapping(value = "/checkData/{username}/{password}", method = RequestMethod.POST)
public String Authentication(@PathParam("username") String username, @PathParam("password") String password) {

}

如果您想使用现有代码并且不想更改后端,则必须调整前端。由于您的后端现在需要 url 中的查询参数,因此您需要在前端发送这些参数

checkLogin(userInfo : AuthLoginInfo){
     return this.http.post(`${API_URL}/APP/checkData?username=${userInfo.username}&
       password=${userInfo.password}`,{},{responseType: 'text'})
  }

推荐阅读