【问题标题】:Type error in mean stack post method平均堆栈发布方法中的类型错误
【发布时间】:2018-04-15 04:11:54
【问题描述】:

平均堆栈

我一直在努力

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

尝试执行此代码时(所有变量,包括模块都在代码的其他部分定义)。使用 GET 方法时,我的代码运行良好。但是对于 POST 方法,它会引发错误。附上下面的截图。

Advance Rest Client POST Method Exception

在下面添加了我的代码。

提前致谢

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

var app = express();

//port Number
const port = 3000;

const route = require('./routes/route');

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

//if connected
mongoose.connection.on('connected', () => {
  console.log("Mongo DB Connected successfully");
});

//if not connected
mongoose.connection.on('error', (err) => {
  if (err) {
    console.log('Error in connecting to the MongoDB');
  }
});

//adding middleware cors
app.use(cors());

//routes will happen here
app.use('/api', route);

//adding middleware
app.use(bodyparser.json());

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

//Testing
app.get('/', (req, res) => {
  res.send("Hello Vinoth");
});

app.get('/yahoo', (req, res) => {
  res.send("Hello Vinoth");
});

//Connection
app.listen(port, () => {
  console.log("Server started at port:" + port);
});

//route.js
const express = require('express');
const router = express.Router();

const Contact = require('../models/contacts');

// retrieving details
router.get('/contacts', (req, res, next) => {
  Contact.find(function(err, contacts) {
    res.json(contacts);
  });
});

// Add Contacts
//Add contact
router.post('/contact', (res, req, next) => {
  console.log('Insides');
  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'
      });
    }
  });
});

// Delete Contacts
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;

//contacts.js
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);

【问题讨论】:

    标签: node.js mongodb rest express


    【解决方案1】:

    尝试在app.use('/api', route) 之前移动app.use(bodyparser.json())。希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      首先你需要声明

      //adding middleware
      app.use(bodyparser.json());
      

      在使用所有路线之前。所以你需要更新你的app.js,比如:

      //adding middleware
      app.use(bodyparser.json());
      
      //routes will happen here
      app.use('/api', route);
      

      此外,您还需要像这样重构 route.js 代码:

      //Add contact
      router.post('/contact', (res, req, next) => {
      
          const {
              first_name,
              last_name,
              phone
          } = req.body;
      
          let newContact = new Contact({
              first_name,
              last_name,
              phone
          });
      
          newContact.save((err, contact) => {
      
              if (err) {
                  res.json({
                      msg: 'Failed to add contact'
                  });
              } else {
                  res.json({
                      msg: 'Contact added successfully'
                  });
              }
      
              });
      });
      

      【讨论】:

      • 上述解决方案对我不起作用。我仍然遇到同样的错误。
      • 还需要将app.use(express.static(path.join(__dirname, 'public')));这行代码移到app.use('/api', route);之前
      猜你喜欢
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 2020-08-05
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      相关资源
      最近更新 更多