Next.js GraphQL API报错求助:POST body缺失等错误排查
问题排查与解决
问题根源
Next.js 13的API路由默认启用了自动JSON body解析,而apollo-server-micro依赖micro库自行解析请求体,两者的解析逻辑冲突,导致Apollo Server无法读取到有效的POST请求体,从而抛出POST body missing, invalid Content-Type, or JSON object has no keys错误。
解决方案
在你的src/pages/api/graphql.ts文件中添加Next.js API路由配置,禁用默认的body解析,让apollo-server-micro独立处理请求体解析。
修改后的完整代码
import { ApolloServer, gql } from 'apollo-server-micro'; import type { NextApiRequest, NextApiResponse } from 'next'; // 禁用Next.js默认body解析,交由Apollo Server处理 export const config = { api: { bodyParser: false, }, }; const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello World', }, }; const apolloServer = new ApolloServer({ typeDefs, resolvers, }); const startServer = apolloServer.start(); export default async function handler( req: NextApiRequest, res: NextApiResponse ) { // CORS配置保留 res.setHeader('Access-Control-Allow-Credentials', 'true'); res.setHeader( 'Access-Control-Allow-Origin', 'https://studio.apollographql.com' ); res.setHeader( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ); if (req.method === 'OPTIONS') { res.end(); return; } await startServer; await apolloServer.createHandler({ path: '/api/graphql', })(req, res); }
验证方法
使用curl命令测试接口:
curl -X POST http://localhost:3000/api/graphql \ -H "Content-Type: application/json" \ -d '{"query": "{ hello }"}'
应返回预期结果:
{ "data": { "hello": "Hello World" } }
补充说明
- 禁用默认body解析后,Apollo Server会通过
micro库正确读取原始请求流并解析JSON,彻底避免与Next.js内置解析逻辑的冲突。 - 若后续需在该路由中手动处理请求体,可使用
micro提供的json/urlencoded工具函数解析,但GraphQL场景下无需额外操作。
内容的提问来源于stack exchange,提问作者Ash N.
相关产品推荐
相关产品推荐

