skip to Main Content

How to slove this problem Please help me


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>

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

Input output

=====

how to solve this problem Please help. if you know anyone how to slove please explain .share your code please. I will try to slove this problem around 5days.but i canot slove this problem.

enter image description hereenter image description hereenter image description here

2

Answers


  1. In your <form> remove the enctype="multipart/form-data" so just have:

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

    This will send your form as the default application/x-www-form-urlencoded so that now your express.urlencoded() function can parse the data. At the minute req.body will not have your parsed form data so you won’t be able to add data to mongodb.

    If you want to send multipart/form-data for something like a file upload then you will need something like multer to parse the data.

    You can improve your code by catching errors and logging them. This will help you debug in the future. Update your route handler callback function to use try/catch like so:

    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",
          })
       }
    });
    

    Lastly, becuase you have created your model like this:

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

    Mongoose will look for a collection named userdatas because:

    The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name.

    Therefore if your collection is named users then when you create your model you need to use:

    const UserModel= mongoose.model("User",userSchema);
    
    Login or Signup to reply.
  2. It looks like your code is generally correct, but there are a couple of improvements and checks you can make to ensure the data is being sent and received properly:

    1. Body Parsing Order:
    You are using both body-parser and express.json() to parse the request body. It’s better to stick with express.json() alone, as it is included in Express by default.

    Replace:

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

    with:

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

    Remove the body-parser import and its usage.

    2. Form Data Encoding:
    Your try-catch block for connecting to the database is not handling the promise returned by mongoose.connect. You should use the await keyword to handle it properly.

    Replace:

    mongoose.connect(URL);
    

    with:

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

    To prevent empty data from being posted to MongoDB, you should add validation checks before saving the data. Specifically, you should check that the required fields (in this case, name and password) are not empty before attempting to save the user.

    Here’s an updated version of your app.post("/reg", async (req, res) => { route with validation checks:

    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",
        });
    }
    });
    

    This updated code does the following:

    • Destructures name and password from req.body for easier validation.
    • Checks if name and password are provided. If not, it returns a 400 Bad Request response.
    • Checks if name and password are not empty strings after trimming whitespace. If empty, it returns a 400 Bad Request response.
    • If all checks pass, it creates a new user and attempts to save it. If there’s an error during the save, it returns a 500 Internal Server Error response.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search