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

Next.js中TypeScript验证后客户端数据无法存入MongoDB问题

Next.js + MongoDB原生驱动:请求体为null导致数据存入全null的解决方案

问题根源

  1. 错误混用Express框架:在Next.js App Router的API路由中引入并使用Express完全没必要,App Router有自己的请求处理机制,app.use(express.json())这类中间件根本不起作用,导致请求体无法解析。
  2. 请求体获取方式错误:直接访问req.body不符合Next.js API路由的规范,必须通过await req.json()来解析JSON格式的请求内容。
  3. 类型使用错误:误用了Express的Request类型,应该使用Next.js自带的NextRequest类型(从next/server导入)。

修正后的后端代码

import { NextResponse, type NextRequest } from "next/server";
import { MongoClient, MongoClientOptions } from "mongodb";

interface CustomMongoClientOptions extends MongoClientOptions {
  useUnifiedTopology?: boolean;
}

export async function POST(req: NextRequest): Promise<NextResponse> {
  try {
    // 正确解析JSON请求体
    const reqBody = await req.json();
    console.log("Received data:", reqBody);

    const {
      first_name = "",
      last_name = "",
      email = "",
      job_title = "",
      company_name = "",
      website_name = "",
      help = "",
      services = "",
      info = "",
    } = reqBody;

    console.log("firstname", first_name);

    const uri: string = process.env.MONGODB_URI || "";
    if (!uri) {
      throw new Error("MONGODB_URI环境变量未配置");
    }

    const client = new MongoClient(uri, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
    } as CustomMongoClientOptions);

    await client.connect();
    const collection = client.db("codeseo").collection("userdata");
    
    const doc = {
      first_name,
      last_name,
      email,
      job_title,
      company_name,
      website_name,
      help,
      services,
      info,
    };
    
    await collection.insertOne(doc);
    await client.close();

    return NextResponse.json({ message: "数据已成功存入MongoDB" }, { status: 200 });
  } catch (error) {
    console.error("存入MongoDB失败:", error);
    return NextResponse.json({ message: "数据存入失败" }, { status: 500 });
  }
}

关键修正说明

  • 移除所有Express相关代码,改用Next.js官方的NextRequest类型处理请求。
  • 通过await req.json()正确解析前端发送的JSON请求体,这是App Router API路由获取请求数据的标准方式。
  • 增加了MONGODB_URI环境变量的校验,避免因空连接字符串导致数据库连接失败。
  • 优化响应格式,返回结构化JSON对象并设置正确的HTTP状态码,便于前端处理结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:21:23