使用 Node JS html 在 Mongodb 数据库中发布空数据

Empty data getting posted in Mongodb database using Node JS html

提问人:Biswadeb Rajbongshi 提问时间:11/17/2023 最后编辑:jQueenyBiswadeb Rajbongshi 更新时间:11/17/2023 访问量:46

问:

如何解决这个问题请帮帮我


const express=require("express");
const app=express();
const bodyparser=require("body-parser");
const cors=require("cors");
const mongoose=require("mongoose");
const PORT=4000;
app.use(cors());
app.use(express.urlencoded({extended:false}));
app.use(express.json());
app.use(bodyparser.urlencoded({extended:true}));

const URL='mongodb+srv://username:[email protected]/UserDB';
 const userSchema=new mongoose.Schema({
    name:{
        type:String
    },
    password:{
        type:String
    }
 });
 const UserModel= mongoose.model("userData",userSchema);

app.get("/",(req,res)=>{
    res.send("hello ")
})
app.get("/reg",(req,res)=>{
    res.sendFile(__dirname+ "/./index.html")

})
app.post("/reg",async(req,res)=>{

    const newUser= new UserModel(req.body);
    await newUser.save();
   res.status(201).json({
        meg:"User created",
    })

});
mongoose.connect(URL)
try {
    console.log("Db is conected");
    
} catch (error) {
    console.log("Db is not conected");
    console.log(error);
    process.exit(1);
    
}

app.listen(PORT, ()=>{
    console.log(`Server is running http://localhost:${PORT}`)
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <a href="/">Home</a>
    <div class="container">
        <h1>Register From</h1>
        <form action="/reg" method="POST" enctype="multipart/form-data">
            <input type="text" name="name" placeholder="enter your name">
            <input type="password" name="password" placeholder="enter your name">

            <input type="submit" value="Register">
        </form>
    </div>

    
</body>
</html>

============

输入输出

=====

如何解决这个问题请帮忙。如果您知道任何人如何 slove,请解释 .share 您的代码。我会尝试在 5 天左右解决这个问题,但我不能解决这个问题。

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

javascript express mongoose xpath nodejs-server

评论


答:

0赞 jQueeny 11/17/2023 #1

在你的删除中,所以只有:<form>enctype="multipart/form-data"

<form action="/reg" method="POST">

这会将您的表单作为默认表单发送,以便现在您的函数可以解析数据。目前没有解析的表单数据,因此您将无法向mongodb添加数据。application/x-www-form-urlencodedexpress.urlencoded()req.body

如果你想发送文件上传之类的东西,那么你将需要像multer这样的东西来解析数据。multipart/form-data

您可以通过捕获错误并记录错误来改进代码。这将帮助您在将来进行调试。更新路由处理程序回调函数以如下所示使用:try/catch

app.post("/reg",async(req,res)=>{
   try{
      const newUser= new UserModel(req.body);
      await newUser.save();
      res.status(201).json({
         message:"User created",
      })
   }catch(err){
      console.log(err);
      res.status(400).json({
         error: "Error on server",
      })
   }
});

最后,因为你已经创建了这样的模型:

const UserModel= mongoose.model("userData",userSchema);

Mongoose 将寻找一个集合,因为:userdatas

第一个参数是模型所针对的集合的单数名称。Mongoose 会自动查找模型名称的复数小写版本

因此,如果您的集合已命名,那么在创建模型时,您需要使用:users

const UserModel= mongoose.model("User",userSchema);

评论

0赞 Biswadeb Rajbongshi 11/17/2023
非常感谢你.after删除此代码<enctype=“multipart/form-data” > 终于解决了这个问题
0赞 jQueeny 11/17/2023
@BiswadebRajbongshi作为新用户,如果您觉得答案有用,请考虑标记为已接受
0赞 Engr. Md. Muslim Uddin Arju 11/17/2023 #2

看起来您的代码通常是正确的,但您可以进行一些改进和检查,以确保正确发送和接收数据:

1. 正文解析顺序:您同时使用 body-parser 和 express.json() 来解析请求正文。最好单独使用 express.json(),因为它默认包含在 Express 中。

取代:

app.use(bodyparser.urlencoded({ extended: true }));

跟:

app.use(express.urlencoded({ extended: false }));

删除 body-parser 导入及其用法。

2. 表单数据编码:用于连接到数据库的 try-catch 块未处理 mongoose.connect 返回的 promise。您应该使用 await 关键字来正确处理它。

取代:

mongoose.connect(URL);

跟:

await mongoose.connect(URL, { useNewUrlParser: true, useUnifiedTopology: true });

为防止将空数据发布到 MongoDB,应在保存数据之前添加验证检查。具体而言,在尝试保存用户之前,应检查必填字段(在本例中为名称和密码)是否不为空。

这是带有验证检查的 app.post(“/reg”, async (req, res) => { route 的更新版本:

app.post("/reg", async (req, res) => {
const { name, password } = req.body;

// Check if required fields are provided
if (!name || !password) {
    return res.status(400).json({
        error: "Name and password are required fields.",
    });
}

// Check if name and password are not empty
if (name.trim() === "" || password.trim() === "") {
    return res.status(400).json({
        error: "Name and password cannot be empty.",
    });
}

const newUser = new UserModel({ name, password });

try {
    await newUser.save();
    return res.status(201).json({
        msg: "User created",
    });
} catch (error) {
    console.error("Error saving user:", error);
    return res.status(500).json({
        error: "Internal Server Error",
    });
}
});

此更新后的代码执行以下操作:

  • 从 req.body 中解构名称和密码,以便于验证。
  • 检查是否提供了名称和密码。否则,它将返回 400 Bad Request 响应。
  • 修剪空格后检查名称和密码是否不是空字符串。如果为空,则返回 400 错误请求响应。
  • 如果所有检查都通过,它将创建一个新用户并尝试保存它。如果在保存过程中出现错误,它将返回 500 Internal Server Error 响应。