React中出现Uncaught (in promise) SyntaxError: Unexpected end of JSON input错误求助
向服务器发送新产品数据时触发错误:Uncaught (in promise) SyntaxError: Unexpected end of JSON input,但传入的JSON对象并非空值。
相关代码:
const newProductsInfos = { title: newProductTitle, price: newProductPrice, count: newProductCount, img: newProductImg, popularity: newProductPopularity, sale: newProductSale, colors: newProductColors, }; const addNewProduct = (event) => { event.preventDefault(); fetch(`http://localhost:8000/api/products`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newProductsInfos), }) .then((res) => res.json()) .then((resullt) => { console.log(resullt); }); };
打印的响应信息:
Response {type: 'cors', url: 'http://localhost:8000/api/products', redirected: false, status: 200, ok: true, …}
body : ReadableStream
bodyUsed : false
headers : Headers {}
ok : true
redirected : false
status : 200
statusText : "OK"
type : "cors"
url : "http://localhost:8000/api/products"
[[Prototype]] : Response
问题原因与解决办法
原因
res.json()方法要求服务器返回合法的JSON格式内容,但当前服务器仅返回了200状态码,却没有返回任何JSON数据(从响应信息的bodyUsed: false和空Headers可以看出),解析空内容时就会触发JSON语法错误。
解决步骤
修复服务器端逻辑:确保POST接口在处理完成后,返回有效的JSON响应,比如成功时返回:
{ "status": "success", "message": "产品添加完成" }即使是错误场景,也需要返回JSON格式的错误信息,不能只返回状态码。
前端添加容错处理:在解析JSON前先判断响应是否有内容,避免空内容解析报错,修改后的代码示例:
const addNewProduct = (event) => { event.preventDefault(); fetch(`http://localhost:8000/api/products`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newProductsInfos), }) .then(async (res) => { // 检查响应是否有内容 const contentLength = res.headers.get('content-length'); if (!contentLength || parseInt(contentLength) === 0) { return { status: 'success', message: '产品已成功添加' }; } // 有内容时再解析JSON return res.json(); }) .then((result) => { console.log(result); }) .catch(err => { console.error('请求异常:', err); }); };调试方法:打开浏览器开发者工具的「网络」面板,找到该POST请求,查看「响应」标签页,确认服务器实际返回的内容,快速定位问题根源。
内容的提问来源于stack exchange,提问作者Mohammad Askari

