簡體   English   中英

節點JS | TypeError:無法讀取未定義的屬性“ first_name”

[英]Node JS | TypeError: Cannot read property 'first_name' of undefined

我只是從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;

現在,我正在嘗試使用郵遞員在數據庫(Mongo DB)中添加一些記錄,但是它引發了一條錯誤消息,提示“ TypeError:在router.post(C:\\ Mean App \\ ContactList無法讀取未定義的屬性'first_name') \\ routes \\ route.js:16:25)“

在郵遞員中,對於標頭,我使用的是“ 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);

謝謝。

您將不得不將body-parser移至use路線上方,並且應該可以工作

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

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

Express API v4.x

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

...

中間件功能是順序執行的,因此中間件包含的順序很重要。

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

為了始終安全起見,您的路由應該始終排在所有中間件之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM