React+Next.js+GraphCMS博客提交评论时GraphQL字段不匹配报错求解
问题原因
从报错信息可以定位到两个核心问题:
- GraphQL Schema不匹配:你的GraphCMS中
Comment模型的字段定义和你mutation中写的name字段不符,GraphCMS的CommentCreateInput输入类型中没有name这个字段 - 请求内容破损:报错中展示的GraphQL查询语句存在截断、乱码的情况,说明前端提交请求时参数传输异常
解决方案
步骤1:修正GraphCMS字段匹配
- 登录你的GraphCMS后台,进入当前项目的Schema界面,找到
Comment模型 - 查看你设置的姓名字段的实际API ID:
- 如果字段API ID是
authorName,就把mutation中name: $name改成authorName: $name - 如果是其他命名,按照你实际设置的API ID对应修改即可
- 同时确认邮箱、评论内容、关联文章的字段API ID也和mutation中写的一致
- 如果字段API ID是
步骤2:修复请求传输问题
- 检查
../services中的submitComment方法,确保POST请求的请求头正确设置了Content-Type: application/json,且请求体是经过JSON.stringify()序列化的正确格式,示例的正确submitComment写法:
export const submitComment = async (commentObj) => { const res = await fetch('/api/comments', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(commentObj) }) return res.json() }
- 修改
pages/api/comments.js中的请求参数传递,显式传入解构后的参数,避免多余字段干扰:
// 把原来的 const result = await graphQLClient.request(query, req.body); // 改成 const result = await graphQLClient.request(query, { name, email, comment, slug });
步骤3:修复代码小问题
修正localStorage移除逻辑的错误,removeItem方法只需要传入键名不需要传入值:
// 原来的错误写法 window.localStorage.removeItem("name", name); window.localStorage.removeItem("email", email); // 改成正确写法 window.localStorage.removeItem("name"); window.localStorage.removeItem("email");
内容的提问来源于stack exchange,提问作者Sudhanshu Shekhar
相关产品推荐
相关产品推荐

