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直接原因)
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) }服务层逻辑修复:当前代码中若
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
相关产品推荐
相关产品推荐

