我刚开始使用 MEAN 应用程序,但在向数据库中添加数据时遇到了困难。所以请帮我找到解决方案。
这是根文件,应用程序的入口点
//Importing modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');
var app=express();
const route=require('./routes/route');
//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
mongoose.connection.on('connected',()=>{
console.log("Successfully established a connection to mongodb Database ")
});
//on error
mongoose.connection.on('error',(err)=>{
if(err){
console.log("Failed to established a connection "+err);
}
});
const port=3000;
//For routing
app.use('/api',route);
//Adding middleware -cors
app.use(cors());
//body-parser
app.use(bodyparser.json());
//Static Files
app.use(express.static(path.join(__dirname,'public')));
//port no
app.get('/',(req,res)=>{
res.send('Foobar');
});
app.listen(port,()=>{
console.log("Server started listening to port "+port);
})
这是我的路线文件,
const express = require('express');
const router = express.Router();
// fetching the schema
const Contact = require('../Models/contacts');
//Retriving the contacts
router.get('/contacts', (req,res,next)=>{
Contact.find(function(err,contacts){
// Sending to client in json format
res.json(contacts);
});
});
// Adding Contacts
router.post('/contact', (req,res,next)=>{
let newContact = new Contact({
first_name : req.body.first_name,
last_name : req.body.last_name,
phone : req.body.phone
});
newContact.save((err,contact)=>{
if(err){
res.json({msg: "Failed to add contact."});
}else{
res.json({msg:"Contact added sucessfully"});
}
});
});
//Deleteing contact
router.delete('/contact/id',(req,res,next)=>{
Contact.remove({_id:req.params.id},function(err,result){
if(err){
res.json(err);
}else{
res.json(result);
}
})
});
module.exports=router;
现在,我正在尝试使用 postman 在 DB (Mongo DB) 中添加一些记录,但它抛出了一条错误消息“TypeError: Cannot read property 'first_name' of undefined, at router.post (C:\Mean App\ContactList\routes\route.js:16:25)"
在 postman 中,对于 header ,我使用“Content-type: application/json”,在原始正文中,我像这样添加 JSON 数据,
{
"first_name" : "Siddhesh",
"last_name" : "Mishra",
"phone" : "9594106324"
}
这是我创建模式的代码
const mongoose=require('mongoose');
const ContactSchema = mongoose.Schema({
first_name:{
type:String,
required:true
},
last_name:{
type:String,
required:true
},
phone:{
type:String,
required:true
}
});
const Contact=module.exports=mongoose.model('Contact',ContactSchema);
谢谢。
最佳答案
你必须将 body-parser
移动到路由 use
之上,应该可以工作
//body-parser
app.use(bodyparser.json());
//For routing
app.use('/api',route);
app.use([path,] callback [, callback...])
...
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
关于javascript - Node JS |类型错误 : Cannot read property 'first_name' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590203/