我是Node js和Postman的新手,并且正在从事这个后端项目,以在我的数据库中存储一个随机人员的详细信息。这是我的app.js文件:
var express=require("express");
var app=express();
//database
var mongoose=require("mongoose");
//connecting to database
mongoose.connect("mongodb+srv://mymongohost?retryWrites=true&w=majority",{ useNewUrlParser: true, useUnifiedTopology: true });
//creating user schema
var userSchema=new mongoose.Schema({
name:String,
age: String,
gender: String,
number: String,
location: String
});
var User =mongoose.model("user",userSchema);
//using body parser
var bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:true}));
//Creating a user
/*User.create({
name: "Snehan",
age: "30",
gender: "male",
number: "998899876",
location: "Sample address, near Thane, Mumbai,Mahasrashtra"
})*/
//ROUTES
app.get("/",function(req,res){
res.redirect("/user");
})
//sending all user data
app.get("/user", function(req,res){
User.find({}, function(err,user)
{
if(err)
res.send(err);
else
res.json(user);
})
})
//creating new user data
app.post("/user",function(req,res){
//storing the data received from body
var name=req.body.name;
var age=req.body.age;
var gender=req.body.gender;
var number=req.body.number;
var location=req.body.location;
//creating new object with all details
var newUser={
name:name,
age:age,
gender:gender,
number:number,
location: location
}
User.create(newUser,function(err,newlyCreatedUser){
if(err)
{res.send("Unable to create new user");}
else
{res.send(newlyCreatedUser);}
});
})
app.listen(process.env.PORT || 3000, function() {
console.log("Server started on port 3000");
});
Package.json:
{
"name": "userdetails",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.10.0"
}
}
但是,每当我尝试使用邮递员测试我的代码时,却无法添加用户数据。 这是我发送的帖子请求。但是新创建的User对象看起来像:
{
"_id": "5f37ba449adfe112529f872a",
"__v": 0
}
有人能帮我知道我哪里出错了吗?
答案 0 :(得分:1)
您的应用缺少一个json
主体解析器中间件,因此req.body
为空。将以下行添加到您的应用设置中:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
答案 1 :(得分:0)
您的代码缺少此信息:
app.use(bodyParser.json())