通过AJAX向RestController传JSON时出现400(Bad Request)错误求助
排查AJAX发送JSON到Spring RestController的400 Bad Request问题
我帮你梳理了代码,首先发现一个致命的拼写错误——这大概率是你当前400错误的核心原因:
在你的AJAX配置里,你写的是 date:myJSON,但正确的参数名应该是 data!这个错误会导致请求根本没有携带JSON数据,后端的@RequestBody接收不到有效内容,直接返回400 Bad Request。
第一步:修正AJAX的参数拼写
先把这个错误改掉,再测试。同时还有几个优化点可以一起调整:
$(document).on("click","#stateSave",function(event){ var stateId=parseInt($("#stateId").val()); var countryId=parseInt($("#countryName").val()); alert(countryId); var stateName=$("#stateName").val(); var JSONObject= { "stateId":stateId, "countryId":countryId, "stateName":stateName }; var myJSON = JSON.stringify(JSONObject); console.log(JSONObject); var url = contextPath+"/master/updateState"; $.ajax({ url : url, type:"put", data:myJSON, // 这里把date改成data contentType:'application/json; charset=utf-8', // async: false, // 建议去掉,同步请求会阻塞浏览器主线程 success:function(response) { console.log(response.status); if(response.status) { $(".editor").hide(); $("#countryTable tbody tr").remove(); $(".mainContainer").show(); stateList(); Alert.info(response.data); } else{ Alert.warn(response.errorMessage); } }, // 新增错误回调,方便排查后续问题 error: function(xhr, status, error) { console.log("请求错误详情:", xhr.responseText); } }); });
第二步:排查其他可能的解析问题
如果改完拼写还是报错,再检查以下几个点:
1. 检查State实体类的结构
Spring MVC需要通过无参构造器和getter/setter方法来完成JSON到实体类的绑定,你的State类必须满足这两个条件,比如:
public class State { private Integer stateId; private Integer countryId; private String stateName; // 必须要有无参构造器 public State() {} // 对应所有字段的getter和setter public Integer getStateId() { return stateId; } public void setStateId(Integer stateId) { this.stateId = stateId; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; } public String getStateName() { return stateName; } public void setStateName(String stateName) { this.stateName = stateName; } }
2. 修正Controller的headers初始化问题
你的Controller里headers是类级别的变量且初始化为null,直接调用headers.add()会触发空指针异常,建议在方法内部初始化:
@PutMapping("/updateState") public ResponseEntity<Map<String, Object>> updateState(@RequestBody State theState) { ResponseEntity<Map<String, Object>> responseEntity=null; try { System.out.println(theState); // 方法内部初始化headers HttpHeaders headers = new HttpHeaders(); boolean res =service.updateState(theState) ; if (res) { headers.add("head", "State"); message.put("status", true); message.put("data", "State has been updated successfully !"); responseEntity= new ResponseEntity<>(message, headers, HttpStatus.CREATED); } else { headers.add("head", "null"); message.put("status", false); message.put("errorMessage", " State has not been updated successfully ! "); responseEntity=new ResponseEntity<>(message, headers, HttpStatus.NOT_FOUND); } } catch (Exception e) { e.printStackTrace(); } return responseEntity; }
3. 用浏览器开发者工具验证请求
打开F12的Network标签,找到PUT请求,查看Request Payload是否是你预期的JSON内容,确认数据确实被发送到了后端。
内容的提问来源于stack exchange,提问作者bharath
相关产品推荐
相关产品推荐

