NodeJS :: TypeError:无法读取未定义的属性'first_name'

我正在从教程中学习MEAN堆栈。 当我尝试在我的本地主机上,我得到一个错误。

TypeError:无法读取未定义的属性'first_name'

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

我在网上发现了一些类似的问题。 但我没有find正确的解决scheme。

这是我的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解决scheme,我发现,

路由之前,我应该使用下面的行

 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 

我用Postman来testingAPI

所以我testing了POST方法和下面的内容types选项。

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

这是我的示例input

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

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

你的内容types是{"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)

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