Next.js中JSON输入意外结束错误及评论获取异常求助
问题解决方案
问题1:SyntaxError: Unexpected end of JSON input 及页面持续加载
原因分析
- 接口未返回有效响应体:仅设置
res.status(200)但未发送响应内容,前端fetch请求会一直处于等待状态,导致页面持续加载。 - fetch请求缺少
Content-Type头:发送JSON数据时未声明类型,后端解析req.body可能出现格式异常。 - 未捕获JSON解析错误:直接执行
JSON.parse(req.body),若请求体格式错误会抛出未处理异常。
修改代码
CreateComment接口优化:
export default async function CreateComment(req, res) { try { if (req.method !== 'POST') { return res.status(405).json({ message: '仅支持POST请求' }); } const { name, comment, _id } = JSON.parse(req.body); console.log(name, comment, _id); await client.config({ token: process.env.SANITY_AUTH_TOKEN }).create({ _type: "comment", name, comment, blog: { _type: "reference", _ref: _id }, }); return res.status(200).json({ success: true, message: '评论提交成功' }); } catch (error) { console.error('提交评论失败:', error); return res.status(500).json({ success: false, message: '提交评论失败' }); } }
表单fetch请求优化:
const onSubmit = (data) => { fetch('/api/CreateComment', { method: "POST", headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ ...data, _id }) }) .then(res => res.json()) .then(result => { console.log(result); // 可在此添加提交成功后的逻辑,比如重置表单 }) .catch(error => console.error('表单提交出错:', error)); }
问题2:前端能看到评论对象但无法获取字段值(name返回undefined)
原因分析
- Sanity字段命名差异:Schema中可能定义的是
_name而非name,或字段被嵌套在其他层级。 - GROQ查询未指定字段:获取评论时未明确请求
name等字段,Sanity仅返回基础结构。 - 数据未完全解析:console.log显示的可能是Proxy对象或未展开的响应结构,实际字段名与预期不符。
解决方案
- 修正GROQ查询语句:确保查询时明确指定需要的字段,例如:
*[_type == "comment" && blog._ref == $blogId]{ _id, name, comment, _createdAt }
- 检查Sanity Schema定义:确认
comment文档的字段配置正确:
export default { name: 'comment', type: 'document', fields: [ { name: 'name', type: 'string', title: '评论者姓名' }, { name: 'comment', type: 'text', title: '评论内容' }, { name: 'blog', type: 'reference', to: [{ type: 'blog' }] } ] }
- 验证前端数据结构:通过
Object.keys(comment)查看实际存在的字段名,确认是否有命名偏差:
// 假设comments是从Sanity获取的数组 comments.forEach(comment => { console.log('实际字段:', Object.keys(comment)); console.log('姓名:', comment.name); });
内容的提问来源于stack exchange,提问作者Mohid Naeem
相关产品推荐
相关产品推荐

