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
In your
<form>
remove theenctype="multipart/form-data"
so just have:This will send your form as the default
application/x-www-form-urlencoded
so that now yourexpress.urlencoded()
function can parse the data. At the minutereq.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:Lastly, becuase you have created your model like this:
Mongoose will look for a collection named
userdatas
because:Therefore if your collection is named
users
then when you create your model you need to use: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:
with:
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:
with:
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:
This updated code does the following: