You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js API路由中Prisma创建Category时参数缺失致500错误

解决Next.js API路由提交Prisma数据时的500错误

问题场景

使用Thunder Client发送携带JSON的POST请求:

{"category_name": "Category Name"}

请求返回500内部服务器错误,错误提示:

Invalid `prisma.category.create()` invocation:

{
  data: {
+   category_name: String
  }
}

Argument `category_name` is missing.

原API路由代码:

// api/category/route.js
import prisma from "../../../../lib/prisma";
import { NextResponse } from "next/server";

export async function POST(request){
    const {category_name} = request.body;
    const userCategory = await prisma.category.create({
        data:{
            category_name: category_name
        }
    })
    const data = await userCategory.json();
    return NextResponse.json(data);
}

对应的Prisma Schema中Category模型定义正常,包含必填的category_name字段。

错误原因

  1. Next.js 13+的Route Handlers中,request.body是ReadableStream类型,并非直接解析好的JSON对象,直接解构会导致category_name为undefined,触发Prisma的参数缺失错误。
  2. 原代码中userCategory是Prisma返回的数据库对象,不是Response实例,调用userCategory.json()会引发额外错误。

修正后的API路由代码

// api/category/route.js
import prisma from "../../../../lib/prisma";
import { NextResponse } from "next/server";

export async function POST(request) {
  // 先解析请求体JSON
  const body = await request.json();
  const { category_name } = body;

  // 前置参数校验
  if (!category_name) {
    return NextResponse.json({ error: "category_name 不能为空" }, { status: 400 });
  }

  try {
    const userCategory = await prisma.category.create({
      data: {
        category_name
      }
    });
    // 直接返回Prisma创建后的对象
    return NextResponse.json(userCategory);
  } catch (error) {
    // 捕获并返回错误信息,便于排查
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

额外注意事项

  • 确保请求头Content-Type设置为application/json,Thunder Client默认会自动配置,若手动修改过需检查。
  • 提交产品信息时逻辑一致:先解析请求体,获取product_name、category_id等字段,再调用prisma.products.create(),注意关联字段的正确性。
  • 添加错误捕获可以快速定位问题,比如Prisma的唯一约束冲突(如重复的category_name)会被捕获并返回明确提示。

内容的提问来源于stack exchange,提问作者We_Go

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:07:36