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

Angular调用Spring Boot /update接口报400 Bad Request求助

排查POST /category/update接口400 Bad Request错误

一、核心原因:请求体数据类型不匹配

查看你提供的请求体,workOutSets数组里的第二个对象存在类型错误:

{
  "weight": "12.5",
  "rep": "15"
}

这里weight和rep是字符串类型,但后端WorkOutSet实体类中这两个字段应为数值类型(比如Double、Integer)。Spring Boot的Jackson序列化组件无法将字符串自动转为数值,直接触发反序列化异常,导致400 Bad Request。

解决方法:

  • Angular端赋值时确保参数为数值类型:
    this.workOutSet.weight = Number(this.weight); // 显式转换为数字
    this.workOutSet.rep = Number(this.reps);
    
  • Postman测试时,将字符串形式的数值改为纯数字:
    {
      "weight": 12.5,
      "rep": 15
    }
    

二、其他潜在优化点(非400直接原因)

  1. HTTP方法规范:更新操作建议使用PUT而非POST,调整后端接口:

    @PutMapping("/update")
    public ResponseEntity<WorkOutCategory> updateWorkOutCategory(@RequestBody WorkOutCategory workOutCategory) {
        return ResponseEntity.status(HttpStatus.OK).body(workOutCategoryService.updateWorkOutCategory(workOutCategory));
    }
    

    Angular端同步修改请求方法:

    updateWorkOutCategory(category:any) {
      return this.http.put(this.serverURL+"category/update",category)
    }
    
  2. 服务层逻辑修复:当前代码中若findById未找到记录,会新建对象保存,导致“更新”变“新增”。建议抛出异常提示:

    @Override
    public WorkOutCategory updateWorkOutCategory(WorkOutCategory workOutCategory) {
        WorkOutCategory origWorkOutCategory = workOutCategoryRepo.findById(workOutCategory.getCategoryId())
            .orElseThrow(() -> new RuntimeException("训练分类不存在,ID: " + workOutCategory.getCategoryId()));
        origWorkOutCategory.setCategoryName(workOutCategory.getCategoryName());
        origWorkOutCategory.setDescription(workOutCategory.getDescription());
        origWorkOutCategory.setWorkOutsList(workOutCategory.getWorkOutsList());
        return workOutCategoryRepo.save(origWorkOutCategory);
    }
    

三、验证步骤

修改请求体的数值类型后,先用Postman测试/category/update接口,确认能正常返回数据;再调整Angular代码,确保传递参数为数值类型,即可解决400错误。

内容的提问来源于stack exchange,提问作者Deepak Belamana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:13:20