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

使用NextJS+MongoDB+Prisma ORM时请求体无效及POST失败求助

解决Next.js API路由中ReferenceError: title is not defined错误

问题根源

你的API路由中解构req.body时未使用变量声明(const/let),在严格模式下,未声明的变量直接赋值会抛出ReferenceError。同时当前API路由没有限制请求方法,也未实现实际的数据库写入逻辑。

修复方案

1. 修复API路由的解构赋值问题

修改pages/api/posts/index.js,添加变量声明并限制仅处理POST请求:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function handler(req, res) {
  // 仅处理POST请求
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method Not Allowed' });
  }

  try {
    // 添加const声明,正确解构请求体
    const { title, published } = req.body;
    if (!title) {
      throw new Error("Title is missing in request body");
    }

    // 使用Prisma写入数据库
    const post = await prisma.post.create({
      data: {
        title,
        published: published ?? false, // 提供默认值避免undefined
      },
    });

    res.status(201).json(post);
  } catch (error) {
    console.error("Error creating post:", error);
    res.status(400).json({ error: error.message || "Failed to create post" });
  } finally {
    await prisma.$disconnect();
  }
}

2. 前端组件优化(可选)

移除无用输入框,添加复选框控制published状态,优化表单提交逻辑:

import React from "react";

const Posts = () => {
  const [postTitle, setPostTitle] = React.useState<string>("");
  const [published, setPublished] = React.useState<boolean>(false);

  const createPosts = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!postTitle) {
      alert("Title is required");
      return;
    }
    try {
      const apiURL = "/api/posts";
      const requestedData = {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ title: postTitle, published }),
      };
      const response = await fetch(apiURL, requestedData);
      const data = await response.json();
      console.log(data);
      if (!response.ok) {
        alert(`Failed to post : ${postTitle}`);
        return;
      }
      setPostTitle("");
      setPublished(false);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <form onSubmit={createPosts}>
      <input
        type="text"
        value={postTitle}
        onChange={(e) => setPostTitle(e.target.value)}
        placeholder="Enter post title"
      />
      <label className="flex items-center gap-2">
        <input
          type="checkbox"
          checked={published}
          onChange={(e) => setPublished(e.target.checked)}
        />
        Mark as published
      </label>
      <button type="submit" className="text-white">
        Create Post
      </button>
    </form>
  );
};

export default Posts;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:43:24