2017-05-12 72 views
2

我正在从教程中学习MEAN堆栈。当我在我的本地主机上尝试时,出现错误。NodeJS :: TypeError:无法读取未定义的属性'first_name'

TypeError: Cannot read property 'first_name' of undefined

at router.post (/var/www/html/mean/contactlist/routes/route.js:17:28)

我在网上发现了一些类似的问题。但我没有找到正确的解决方案。

这里是我的app.js文件

//importing modules 
var express = require('express'); 
var mongoose = require('mongoose'); 
var bodyparser = require('body-parser'); 
var cors = require('cors'); 
var path = require('path'); //core module 


// calling express method 
var app = express(); 


//connect to mongodb 
mongoose.connect('mongodb://localhost/27017/contactlist'); 

//on connection 
mongoose.connection.on('connected',() => { 
    console.log("connected to database database mongodb @ 27017 "); 
}); 

mongoose.connection.on('error', (err) => { 

    if(err){ 
     console.log('Error in Database connection : ' + err); 
    } 
}); 

//adding middleware cors 
app.use(cors()); 

//adding body parser 
app.use(bodyparser.json()); 

//adding static files 
app.use(express.static(path.join(__dirname, 'public'))); 

//setting port no 
const port = 3000; 


//routing 
var route = require('./routes/route'); 

//using the route 
app.use('/api', route); 


//testing server 
app.get('/', (req, res)=>{ 

    res.send('foobar'); 

}); 

//binding the server with port no (callback) 

app.listen(port,() =>{ 
    console.log('Server Started at Port : '+ port); 


}); 

从StackOverflow的解决方案,我发现,

我应该使用以下行前路由

app.use(bodyparser.json()); 

所以我改变了它。

而且我./routes/route.js

const express = require('express'); 
const router = express.Router(); 

const Contact = require('../models/contacts'); 

//Retrieving contacts 
router.get('/contacts', (res, req, next) => { 
    contact.find(function(err,contacts){ 
     res.json(contacts); 
    }) 

}); 

//Add contact 
router.post('/contact', (res, req, 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 successfully'}); 
     } 

    }); 
}); 


//Deleting Contact 
router.delete('/contact/:id', (res, req, next) => { 
    contact.remove({_id: req.params.id }, function(err, result){ 

     if(err){ 
      res.json(err); 
     } 
     else{ 
      res.json(result); 
     } 

    }); 
}); 


module.exports = router; 

依赖的package.json

"dependencies": { 
    "body-parser": "^1.17.1", 
    "cors": "^2.8.3", 
    "express": "^4.15.2", 
    "mongoose": "^4.9.8" 
    } 

而且中的NodeJS的版本是

v7.10.0 

我用邮递员测试了API

所以我测试了POST方法和下面的内容类型选项。

{"Content-Type":"application/x-www-form-urlencoded"} 

这是我的样本输入

{ 
    "first_name" : "RENJITH", 
    "last_name" : "VR", 
    "phone" : "1234567890" 
} 

它是一个版本的问题?请给我建议正确的编码方式。

+1

哪里可以得到这个错误?在这个错误你总是得到文件和线.. –

+0

@NedimHozić - 'first_name:req.body.first_name' –

回答

1

你的内容类型是{"Content-Type":"application/x-www-form-urlencoded"} 为了支持数据的URL编码的机构,你需要使用这样的:你用什么

app.use(bodyparser.urlencoded({  // to support URL-encoded bodies 
    extended: true 
})); 

是JSON编码的数据,如POST: {"name":"foo","color":"red"}

编辑:

您的路线参数的顺序是错误的。这不是router.post('/contact', (res, req, next)

它实际上router.post('/contact', (req, res, next)

第一个参数是请求,二是响应。

+0

谢谢你的解决方案。我认为这是'bodyparser'。不'bodyParser'。对?我试过了。它不工作! –

+0

您定义了您的变量bodyparser,因此您应该使用它。我编辑了我的帖子以反映这一点。添加我提到的代码,但使用bodyparser而不是bodyParser,并尝试再次发送请求。 (确保你重新启动了你的服务器)。它应该工作。 –

+0

如果您在Postman中将Content-Type标头设置为“application/json”,则应该无需添加urlencoded中间件即可工作。 –

相关问题