NodeJS :: TypeError: Cannot read property 'first_name' of undefined
NodeJS :: TypeError: Cannot read property 'first_name' of undefined
我正在通过教程学习 MEAN 堆栈。当我在本地主机上尝试时,出现错误。
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);
});
我从一个 Whosebug 解决方案中发现,
我应该在 routing
之前使用以下行
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 测试了 API
所以我使用 POST 方法和以下内容类型选项进行了测试。
{"Content-Type":"application/x-www-form-urlencoded"}
这是我的示例输入
{
"first_name" : "RENJITH",
"last_name" : "VR",
"phone" : "1234567890"
}
是不是版本问题?请建议我正确的编码方式。
您的内容类型是{"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)
第一个参数是请求,第二个是响应。
只需在路由 (app.js) 之前移动顶部的 body-parse 行
app.use(bodyparser.json());
app.use('/api',route);
我也遇到了同样的问题,但我是这样解决的
在文件的顶部在任何路由之前和 require
语句之后使用
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
然后在post请求路由中使用res.json()
这里是示例代码:
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.sendFile(__dirname + './index.html')
})
app.post("/name", (req, res) => {
let fullName = req.body.first + ' ' + req.body.last;
res.json({ name: fullName })
});
我正在通过教程学习 MEAN 堆栈。当我在本地主机上尝试时,出现错误。
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);
});
我从一个 Whosebug 解决方案中发现,
我应该在 routing
之前使用以下行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 测试了 API
所以我使用 POST 方法和以下内容类型选项进行了测试。
{"Content-Type":"application/x-www-form-urlencoded"}
这是我的示例输入
{
"first_name" : "RENJITH",
"last_name" : "VR",
"phone" : "1234567890"
}
是不是版本问题?请建议我正确的编码方式。
您的内容类型是{"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)
第一个参数是请求,第二个是响应。
只需在路由 (app.js) 之前移动顶部的 body-parse 行
app.use(bodyparser.json());
app.use('/api',route);
我也遇到了同样的问题,但我是这样解决的
在文件的顶部在任何路由之前和 require
语句之后使用
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
然后在post请求路由中使用res.json()
这里是示例代码:
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.sendFile(__dirname + './index.html')
})
app.post("/name", (req, res) => {
let fullName = req.body.first + ' ' + req.body.last;
res.json({ name: fullName })
});