向Next.js API路由发送POST请求时出现500内部服务器错误
Next.js API路由POST请求返回500内部服务器错误
在向Next.js的API路由发送POST请求时遇到500 Internal Server Error,多次清除缓存、重启服务器均无法解决问题。以下是相关代码:
API路由代码(createComment.ts)
import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLIC_SANITY_DATSET, projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, useCdn: process.env.NODE_ENV === "production", token: process.env.SANITY_API_TOKEN } const client = sanityClient(config); export default async function createComment( req: NextApiRequest, res: NextApiResponse ) { const {_id, name, email, comment} = req.body try { await client.create({ _type: 'comment', post: { _type: "reference", _ref: _id }, name, email, comment }) } catch (error) { return res.status(500).json({message: "Couldn't submit comment", error}) } console.log("Comment submitted") res.status(200).json({ message: 'Comment Submitted Successfully' }) }
前端请求代码
const onSubmit: SubmitHandler<IFormInput> = (data) => { fetch("/api/createComment", { method: "POST", body: JSON.stringify(data), }) .then(() => { console.log(data); }) .catch((error) => { console.log(error); }); };
排查方向:
前端请求未设置Content-Type:使用
JSON.stringify(data)发送请求时,必须设置headers: { 'Content-Type': 'application/json' },否则Next.js无法解析请求体,导致req.body为undefined,解构_id等字段时会抛出错误。修改后的fetch代码:fetch("/api/createComment", { method: "POST", headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), })Sanity客户端配置问题:写入操作不能使用CDN,需将
useCdn固定设为false,因为CDN仅支持只读请求。修改config:const config = { dataset: process.env.NEXT_PUBLIC_SANITY_DATSET, projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, useCdn: false, // 写入操作必须禁用CDN token: process.env.SANITY_API_TOKEN }环境变量加载异常:
SANITY_API_TOKEN是服务器端环境变量,不能加NEXT_PUBLIC_前缀,确保它在.env.local文件中正确配置,且服务器已重启加载最新环境变量。同时检查NEXT_PUBLIC_SANITY_DATSET是否拼写正确(当前代码中是DATSET,可能应为DATASET)。Sanity Schema不匹配:确认Sanity后台的
comment类型已正确定义,包含post(reference类型,指向post文档)、name、email、comment(字符串类型)字段,且没有未满足的必填项。错误序列化问题:catch块中直接返回
error对象可能导致JSON序列化失败,建议提取错误信息:catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; return res.status(500).json({message: "Couldn't submit comment", error: errorMessage}) }
内容的提问来源于stack exchange,提问作者Armaghan Hayat
相关产品推荐
相关产品推荐

