最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS :: TypeError: Cannot read property 'first_name' of undefined - Stack Overflow

programmeradmin4浏览0评论

I was learning the MEAN stack from a tutorial. When I tried on my localhost, I got an error.

TypeError: Cannot read property 'first_name' of undefined

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

I found some similar questions on the internet. But I didn't find the correct solution.

Here is my app.js file

//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);


});

From a stackOverflow solution, I found,

I should use the following line before routing

app.use(bodyparser.json());

So I changed it.

And my ./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;

Dependencies from package.json

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

And the version of the nodejs is

v7.10.0

I used Postman to test the API

So I tested with POST method and following content-type option.

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

This was my sample input

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

Is it a version issue? Please suggest me the correct way of coding.

I was learning the MEAN stack from a tutorial. When I tried on my localhost, I got an error.

TypeError: Cannot read property 'first_name' of undefined

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

I found some similar questions on the internet. But I didn't find the correct solution.

Here is my app.js file

//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);


});

From a stackOverflow solution, I found,

I should use the following line before routing

app.use(bodyparser.json());

So I changed it.

And my ./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;

Dependencies from package.json

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

And the version of the nodejs is

v7.10.0

I used Postman to test the API

So I tested with POST method and following content-type option.

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

This was my sample input

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

Is it a version issue? Please suggest me the correct way of coding.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked May 12, 2017 at 15:05 CodingalienCodingalien 3,0472 gold badges24 silver badges32 bronze badges 2
  • 1 Where you can get this error? In this error you always get file and line.. – Nedim Hozić Commented May 12, 2017 at 15:10
  • @NedimHozić - first_name:req.body.first_name – Codingalien Commented May 12, 2017 at 15:11
Add a ment  | 

3 Answers 3

Reset to default 3

Your content type is {"Content-Type":"application/x-www-form-urlencoded"} In order to support URL-encoded bodies of data you need to use this:

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

What you used is for JSON-encoded data, such as POST: {"name":"foo","color":"red"}

EDIT:

The order of your route parameters are wrong. It's not router.post('/contact', (res, req, next)

It's actually router.post('/contact', (req, res, next)

The first parameter is the request, the second is the response.

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

app.use(bodyparser.json());

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

I was facing same issue but this is how it's been solved for me

At the top of the file before any routes and after require statements use

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

then in the post request route use res.json()

here is sample code:

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 }) 
});
发布评论

评论列表(0)

  1. 暂无评论