【问题标题】:NodeJS :: TypeError: Cannot read property 'first_name' of undefinedNodeJS :: TypeError:无法读取未定义的属性'first_name'
【发布时间】:2017-10-11 23:07:53
【问题描述】:

我正在从教程中学习 MEAN 堆栈。当我在本地主机上尝试时,出现错误。

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

在 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

我使用 Postman 测试 API

所以我使用 POST 方法和以下内容类型选项进行了测试。

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

这是我的示例输入

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

是版本问题吗?请建议我正确的编码方式。

【问题讨论】:

  • 在哪里可以得到这个错误?在这个错误中,你总是得到文件和行..
  • @NedimHozić - first_name:req.body.first_name

标签: javascript node.js express mean-stack


【解决方案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)

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

【讨论】:

  • 感谢您的解决方案。我认为是bodyparser。不是bodyParser。正确的?我试过了。它不工作!
  • 你定义了你的变量 bodyparser,所以你应该使用它。我编辑了我的帖子以反映这一点。添加我提到的代码,但使用 bodyparser 而不是 bodyParser,并尝试再次发送请求。 (确保您重新启动了服务器)。它应该可以工作。
  • 如果您在 Postman 中将 Content-Type 标头设置为“application/json”,它应该可以工作,甚至不需要添加 urlencoded 中间件。
  • 我正在使用 nodemon。所以我不需要重新启动服务器。对吗?
  • 哦,你函数的参数顺序不对。切换 res 和 req 的顺序,应该可以了。
【解决方案2】:

Just Move lines body-parse at top before route (app.js)

app.use(bodyparser.json());

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

【讨论】:

    【解决方案3】:

    我遇到了同样的问题,但这是为我解决的方法

    在任何路由之前和require 语句使用之后的文件顶部

    app.use(bodyParser.urlencoded({extended: true}))
    app.use(bodyParser.json())
    

    然后在发布请求路由中使用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 }) 
    });
    

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 2019-02-10
      • 2017-03-06
      • 2019-05-08
      • 2021-07-20
      • 2022-09-23
      • 2022-11-29
      • 2017-08-30
      • 1970-01-01
      相关资源
      最近更新 更多