节点JS | TypeError:无法读取未定义

时间:2017-12-01 09:24:41

标签: javascript json node.js mongodb

我刚开始使用MEAN应用程序,并且在将数据添加到数据库时卡住了。所以请帮我找到解决方案。

这是根文件,应用程序中的入口点

//Importing  modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');

var app=express();
const route=require('./routes/route');

//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');

//on connection
mongoose.connection.on('connected',()=>{
    console.log("Successfully established a connection to mongodb Database ")
});

//on error
mongoose.connection.on('error',(err)=>{
    if(err){
        console.log("Failed to established a connection "+err);
    }
});
const port=3000;
//For routing
app.use('/api',route);

//Adding middleware -cors
app.use(cors());

//body-parser
app.use(bodyparser.json());

//Static Files
app.use(express.static(path.join(__dirname,'public')));

//port no


app.get('/',(req,res)=>{
    res.send('Foobar');
});

app.listen(port,()=>{
    console.log("Server started listening to port "+port);  
})

这是我的路线档案,

const express = require('express');
const router = express.Router();
// fetching the schema
const Contact = require('../Models/contacts');
//Retriving the contacts
router.get('/contacts', (req,res,next)=>{
    Contact.find(function(err,contacts){
        // Sending to client in json format
        res.json(contacts); 
    });
});

// Adding Contacts
router.post('/contact', (req,res,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 sucessfully"});
        }
    });
});

//Deleteing contact
router.delete('/contact/id',(req,res,next)=>{
    Contact.remove({_id:req.params.id},function(err,result){
        if(err){
            res.json(err);
        }else{
            res.json(result);
        }
    })  
});

module.exports=router;

现在,我正在尝试使用postman在DB(Mongo DB)中添加一些记录,但是它在“router.post”(C:\ Mean)中抛出错误“TypeError:无法读取undefined的属性'first_name'应用\ ContactList \路由\ route.js:16:25)“

在postman中,对于标题,我正在使用“Content-type:application / json”,在原始体内,我正在添加这样的JSON数据,

{
    "first_name" : "Siddhesh",
    "last_name" : "Mishra",
    "phone" : "9594106324"
}

这是我的代码,我正在创建架构

const mongoose=require('mongoose');
const ContactSchema = mongoose.Schema({
    first_name:{
        type:String,
        required:true
    },
    last_name:{
        type:String,
        required:true
    },
    phone:{
        type:String,
        required:true
    }
});

const Contact=module.exports=mongoose.model('Contact',ContactSchema);
谢谢。

2 个答案:

答案 0 :(得分:4)

您必须将body-parser移到路线use之上并且应该正常工作

//body-parser
app.use(bodyparser.json());

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

来自Express API v4.x

  

app.use([path,] callback [,callback ...])

     

...

     

中间件功能按顺序执行,因此顺序执行   中间件包含很重要。

答案 1 :(得分:0)

body-parser需要在路线前进行:

//Importing  modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');

var app = express();
const route = require('./routes/route');

//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');

//on connection
mongoose.connection.on('connected', () => {
  console.log("Successfully established a connection to mongodb Database ")
});

//on error
mongoose.connection.on('error', (err) => {
  if (err) {
    console.log("Failed to established a connection " + err);
  }
});

const port = 3000;

//body-parser
app.use(bodyparser.json()); // here


//Adding middleware -cors
app.use(cors());

//Static Files
app.use(express.static(path.join(__dirname, 'public')));

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

app.get('/', (req, res) => {
  res.send('Foobar');
});

app.listen(port, () => {
  console.log("Server started listening to port " + port);
})

为了始终保持安全,您的路线应始终位于所有中间件之后。