Next.js通过内部POST API填充数据库失败求助
接口调用500错误排查求助
前端相关代码
点击触发添加购物车操作的组件代码:
<div className={styles.Panier}> <p onClick={()=>Quantity>0?NewItem(data,Quantity):console.log("Quantity must be more than 0")}>Add To Cart</p> </div>
点击后执行的NewItem函数:
let NewItem = async (data,Qte) => { const response = await fetch('/api/UpdateCart',{ method: "POST", body: JSON.stringify( { Qte, data, cartId: Cookies.get('cart') } ), headers:{ 'Content-Type': 'application/json; charset=utf8' }, }); console.log(response); };
后端接口代码(/api/UpdateCart)
使用Prisma操作数据库的接口实现:
import { PrismaClient } from "@prisma/client"; export default async function handler(req, res) { let prisma = new PrismaClient(); let Id = req.body.Id; let Qte = req.body.Qte; let cartId = req.body.cartId; //Creates the new item and adds it to the cart let newItem = await prisma.item.create({ data: { ProductId: Id, Quantity: Qte, CartId: cartId } }); return res.status(200).json(newItem); }
问题现象
用Postman直接调用该接口时一切正常,但通过前端NewItem函数调用时,出现500内部服务器错误:
POST http://localhost:3000/api/UpdateCart 500 (Internal Server Error)
返回的响应信息:
Response {type: 'basic', url: 'http://localhost:3000/api/UpdateCart', redirected: false, status: 500, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 500 statusText: "Internal Server Error" type: "basic" url: "http://localhost:3000/api/UpdateCart" [[Prototype]]: Response
排查建议
修正请求参数结构不匹配问题
前端NewItem传参时把产品ID放在data对象里,但后端直接从req.body.Id取值,导致参数缺失。需要将后端的参数读取逻辑改为从data中获取ID:let Id = req.body.data.Id; // 替换原有的let Id = req.body.Id;添加错误捕获与日志输出
后端接口缺乏错误处理,无法定位具体报错原因,建议加入try-catch块打印错误:export default async function handler(req, res) { let prisma = new PrismaClient(); try { let Id = req.body.data.Id; let Qte = req.body.Qte; let cartId = req.body.cartId; let newItem = await prisma.item.create({ data: { ProductId: Id, Quantity: Qte, CartId: cartId } }); return res.status(200).json(newItem); } catch (error) { console.error("创建购物车商品失败:", error); return res.status(500).json({error: error.message}); } }前端也需要读取响应的错误详情,而非仅打印Response对象:
let NewItem = async (data,Qte) => { try { const response = await fetch('/api/UpdateCart',{ method: "POST", body: JSON.stringify({ Qte, data, cartId: Cookies.get('cart') }), headers:{ 'Content-Type': 'application/json; charset=utf8' }, }); if (!response.ok) { const errorData = await response.json(); console.error("请求错误:", errorData); } else { const result = await response.json(); console.log("添加成功:", result); } } catch (error) { console.error("网络错误:", error); } };验证CartId有效性
检查前端Cookies.get('cart')是否能正确获取到有效的cartId,Postman调用时可能手动传入了正确值,但前端可能未正确获取,导致Prisma外键约束报错。核对Prisma模型定义
确认Item模型中的ProductId、CartId字段类型,与Product、Cart模型的关联字段类型一致,避免因类型不匹配导致数据创建失败。
内容的提问来源于stack exchange,提问作者Bachar ELkarni
相关产品推荐
相关产品推荐

