[英]Node JS | TypeError: Cannot read property 'first_name' of undefined
Im just starting out with MEAN application, and im stuck while adding data into the database. 我只是从MEAN应用程序开始,而在将数据添加到数据库时就卡住了。 So please help me to find the solution for this.
因此,请帮助我找到解决方案。
This is the root file, entry point in the application 这是根文件,是应用程序中的入口点
//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);
})
And this my route file, 这是我的路线文件
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;
Now, I'm trying to add a few records in DB (Mongo DB) using postman, but it's throwing an error saying "TypeError: Cannot read property 'first_name' of undefined, at router.post (C:\\Mean App\\ContactList\\routes\\route.js:16:25)" 现在,我正在尝试使用邮递员在数据库(Mongo DB)中添加一些记录,但是它引发了一条错误消息,提示“ TypeError:在router.post(C:\\ Mean App \\ ContactList无法读取未定义的属性'first_name') \\ routes \\ route.js:16:25)“
In postman, for header, I'm using "Content-type: application/json" and in raw body, I'm adding JSON data like this, 在邮递员中,对于标头,我使用的是“ Content-type:application / json”,在原始正文中,我添加的是这样的JSON数据,
{
"first_name" : "Siddhesh",
"last_name" : "Mishra",
"phone" : "9594106324"
}
And here is my code where I'm creating schema 这是我创建架构的代码
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);
thank you. 谢谢。
You will have to move body-parser
above the routes use
and should work 您将不得不将
body-parser
移至use
路线上方,并且应该可以工作
//body-parser
app.use(bodyparser.json());
//For routing
app.use('/api',route);
From Express API v4.x 从Express API v4.x
app.use([path,] callback [, callback...])
app.use([path,] callback [,callback ...])
...
...
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
中间件功能是顺序执行的,因此中间件包含的顺序很重要。
body-parser
needs to go before the routes: body-parser
需要走以下路线:
//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;
//body-parser
app.use(bodyparser.json()); // here
//Adding middleware -cors
app.use(cors());
//Static Files
app.use(express.static(path.join(__dirname, 'public')));
// For routing
app.use('/api', route);
app.get('/', (req, res) => {
res.send('Foobar');
});
app.listen(port, () => {
console.log("Server started listening to port " + port);
})
To always be on the safe side your routes should always come last after all middleware. 为了始终安全起见,您的路由应该始终排在所有中间件之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.