node.js快递找不到型号

node.js on express unable to find the model

我的路由器文件中有一个 post 方法,我在其中实例化了 Contact 模型中的一个对象。但是我对 Contact 模型没有定义。错误是

错误:

**TypeError: Cannot read property 'firstname' of undefined**

routes/contact.js

var express = require('express');
var router = express.Router();

var Contact = require("../models/contacts");

router.post('/contact', function(req, res, next) {
   res.send("POST method");
    newContact = new Contact({
      firstname: req.body.firstname,
      lastname: req.body.lastname
   }

models/contacts.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var contactSchema = new Schema({
  firstname:  String,
  lastname: String
});

var Contact = module.exports = mongoose.model('Contact', contactSchema);

您的模型是正确的。您必须使用 body-parser 来解析请求正文。

参见:

https://www.npmjs.com/package/body-parser#examples

在routes/contact.js中添加如下代码

var bodyParser = require('body-parser')
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())