NextJS v13.4评论提交API报错:变量未定义及JSON输入异常
问题:NextJS 13.4评论提交API 500错误(GraphQL变量未定义)
现象
将旧项目迁移到NextJS 13.4后,点击评论提交按钮触发POST http://localhost:3000/api 500 (Internal Server Error),服务器控制台输出ClientError: variable 'name' must be defined,所有GraphQL变量均为undefined。
原因
NextJS 13 App Router的API路由(app/api/route.js)采用了全新的请求处理规范,不再兼容Express风格的req.body直接访问。原代码中直接读取req.body.name等属性,实际获取到的是undefined,导致GraphQL mutation缺少必填变量。
解决方案
修改API路由代码,按照App Router规范解析请求体并返回响应:
- 调用
req.json()异步解析请求体数据 - 使用
NextResponse.json()返回响应(替代原Express风格的res.send)
修改后的代码(app/api/route.js)
import { GraphQLClient, gql } from 'graphql-request'; import { NextResponse } from 'next/server'; // 引入NextResponse const graphqlAPI = process.env.NEXT_PUBLIC_GRAPHCMS_ENDPOINT; const graphcmsToken = process.env.GRAPHCMS_TOKEN; export async function POST(req) { // 移除res参数 // 解析请求体 const { name, email, comment, slug } = await req.json(); const client = new GraphQLClient(graphqlAPI, { headers: { authorization: `Bearer ${graphcmsToken}`, }, }); const query = gql` mutation CreateComment($name: String!, $email: String!, $comment: String!, $slug: String!) { createComment(data: {name: $name, email: $email, comment: $comment, post: {connect: {slug: $slug}}}) { id } } `; const result = await client.request(query, { name, email, comment, slug, }); // 使用NextResponse返回JSON响应 return NextResponse.json(result); }
验证要点
- 重启NextJS服务
- 提交评论后,检查服务器日志是否再无变量未定义的错误
- 前端应显示"Comment submitted for review"成功提示,API返回200状态码
内容的提问来源于stack exchange,提问作者Looming
相关产品推荐
相关产品推荐

