fetch发送PUT请求报400提示需非空请求体但已设置body如何排查
问题修复方案
1. 后端代码核心修复
你的ASP.NET Core控制器接口未指定Person参数的来源,默认会从查询参数/路由中匹配该参数,不会解析请求体的JSON内容,因此会判定参数为空直接返回400,断点自然无法命中。
给Person参数添加[FromBody]注解即可:
[HttpPut("{id}")] public IActionResult Put(int id, [FromBody] Person person) { person.Id = id; try { var updatedPerson = _personRepository.Update(person); if (updatedPerson != null) { return Ok(updatedPerson); } return NotFound(); } catch (ArgumentNullException) { return BadRequest(); } }
2. 前端代码优化
fetch的特性是只要收到服务器响应(包括400、500等错误状态码)都会进入.then(),只有网络层请求失败才会触发.catch(),因此你需要主动判断响应状态,同时可以加日志确认请求体是否正常生成,另外建议给接口路径加根路径前缀避免相对路径拼接错误:
// 先确认序列化后的内容非空 console.log('请求体内容:', JSON.stringify(person)) fetch(`/api/person/${person.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(person) }) .then(response => { // 主动判断请求是否成功 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`) } return response.json() }) .then(() => this.router.navigate(["/"])) .catch(err => console.error('请求错误:', err))
补充排查点
- 确认前端请求的完整URL和Postman请求的URL完全一致,避免拼写、相对路径拼接错误
- 确认
person对象非空,序列化后是合法的JSON格式 - 检查是否存在跨域预检请求(OPTIONS)被拦截的情况,如果后端未配置CORS允许PUT请求,也会导致实际PUT请求未发送,出现无payload的情况
内容的提问来源于stack exchange,提问作者Indigo
相关产品推荐
相关产品推荐

