You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular向SpringBoot API发送POST请求未传递参数问题

问题根源

你的SpringBoot接口用@RequestParam String user,意味着它期望从URL查询参数或者表单提交参数里拿到名为user的字符串,但Angular的http.post默认是把user对象序列化成JSON放在**请求体(Request Body)**里发送的,两者不匹配,所以Spring提示找不到user参数。

解决方案(推荐:改SpringBoot接口,符合REST规范)

直接让Spring接收请求体里的JSON对象,无需手动解析,步骤如下:

  1. 修改LoginController的login方法,把@RequestParam换成@RequestBody,直接接收Login对象:
@RestController
@RequestMapping("/login")
public class LoginController {

    @PostMapping("/login")
    public String login(@RequestBody Login l) throws Exception{
        System.out.println("邮箱:" + l.email + ",密码:" + l.pass);
        if(l.checkUser().equals("ok")){
            if(l.checkPassword().equals("ok")){
                return "logged";
            } else {
                return l.checkPassword();
            }
        }
        return l.checkUser();
    }
}
  1. 给Login类添加无参构造器,因为Spring的Jackson序列化工具需要用无参构造创建实例:
public class Login extends Database{
    public String email;
    public String pass;
    public Statement stm;

    // 新增无参构造器
    public Login() throws Exception{
        // 如果Database类有构造逻辑,确保这里能正常初始化,或者把stm的初始化移到checkUser方法里
    }

    public Login(String email, String pass) throws Exception{
        this.email = email;
        this.pass = pass;
        this.stm = (Statement) this.con.createStatement();
    }
}
  1. Angular代码无需修改,保持原写法即可——它本来就是发送JSON请求体,现在Spring能直接解析了。
备选方案(改Angular发送请求参数,不推荐)

如果非要保留Spring的@RequestParam,可以让Angular把JSON字符串作为请求参数发送:

validateLogin(user:User):Observable<string>{
    const params = new HttpParams().set('user', JSON.stringify(user));
    // 注意第二个参数传空对象,把参数放在第三个options里
    return this.http.post<string>(`http://localhost:8080/login/login`, {}, { params }).pipe(
      map((resp)=>{
        return this.repareString(JSON.stringify(resp));
      })
    )
}

这种方式不推荐,因为JSON字符串作为参数可能存在编码问题,且登录接口用请求体更符合安全规范。

内容的提问来源于stack exchange,提问作者Luis Rosúa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 11:46:05