2017-05-12 70 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中間件即可工作。 –

相關問題