为什么 Next.js 在 TypeScript 验证后无法获取客户端数据并发布到后端?

问题描述 投票:0回答:1

我是一名初学者,在 Next.js 中从 MongoDB 获取数据时遇到问题。客户端运行正常,我已经检查了控制台日志和模式验证。另外,我还使用了 Zod 验证

import { NextResponse } from "next/server";
import { MongoClient, MongoClientOptions } from "mongodb";
import { Request } from "express";
import express from "express";

const app = express();
app.use(express.json());

interface CustomMongoClientOptions extends MongoClientOptions {
 useUnifiedTopology?: boolean;
}

export async function POST(req: Request): Promise<NextResponse> {
 // Explicitly type req and return type
 if (req.method === "POST") {
   try {
     console.log("Received data:", req.body);
     const {
       first_name = "",
       last_name = "",
       email = "",
       job_title = "",
       company_name = "",
       website_name = "",
       help = "",
       services = "",
       info = "",
     } = req.body; // Access req.body directly without await
     console.log("firstname", first_name);

     const uri: string = process.env.MONGODB_URI || ""; // Use environment variable for 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("Data has been saved to MongoDB");
   } catch (error) {
     console.error("Error saving data to MongoDB:", error);
     return NextResponse.json("Data has not been saved");
   }
 } else {
   return NextResponse.json("Method not allowed");
 }
}

“我尝试使用ChatGPT并收到帮助,但数据没有存储在我的数据库中。当我使用req.body控制台日志时,它返回null。我在网上搜索解决方案并在YouTube上找到了很多教程,但它们都使用 Mongoose,如果有人可以提供帮助,请告诉我,如果需要,我还可以提供客户端代码,因此我隐藏了我编写的 URI。 .

输出”

{"_id":{"$oid":"662570bb7dfc4586e4208c18"},"first_name":null,"last_name":null,"email":null,"job_title":null,"company_name":null,"website_name":null,"help":null,"services":null,"info":null}
javascript node.js typescript mongodb next.js
1个回答
0
投票

后端代码看起来是正确的,除了如果未定义 url env var,我可能会建议抛出错误。

返回 null 的日志表明您没有从前端正确调用端点。

© www.soinside.com 2019 - 2024. All rights reserved.