React向JSON Server发送POST请求仅生成ID无数据问题
解决JSON Server仅生成ID、未接收POST数据的问题
核心问题:请求头拼写错误
你的fetch请求headers里的"Contect-Type"是拼写错误,正确字段名应为"Content-Type"。JSON Server依赖这个请求头识别请求体的JSON格式,拼写错误会导致服务器无法解析你发送的values数据,因此仅生成默认ID,其余字段为空。修正后的代码
const onSubmit = (values) => { console.log(values) fetch('http://127.0.0.1:8000/contacts/', { method: 'POST', body: JSON.stringify(values), headers: {"Content-Type": "application/json; charset=UTF-8"} // 修正拼写错误 }).then(response => { // 同步修正拼写错误的变量名responce为response if (!response.ok) { alert("Failed to add") }else{ alert("Contact added") } return response.json(); }).then(data => { console.log('Added', data) // 打印返回数据,确认保存结果 }).catch(error => { // 新增错误捕获,方便排查请求异常 console.error('Request error:', error) alert('Request failed') }) }额外验证点
- 确认
values的结构与JSON Server中contacts集合的字段要求匹配,确保没有键名不对应或嵌套层级问题 - 检查JSON Server的启动配置:确保用
json-server --watch db.json启动,且db.json初始包含"contacts": []数组结构
- 确认
内容的提问来源于stack exchange,提问作者Simon Heavens
相关产品推荐
相关产品推荐

