Nodejs无法发布

问题描述 投票:1回答:1

我对编程非常陌生,并且正在学习教程。

我被困住了,无法使用该代码发布新条目,也无法在此处找到我所缺少的内容。任何帮助将不胜感激。

[当我尝试使用邮递员发帖时,我收到验证错误,而当我试图获取值时,我却得到了[]。

编辑:错误消息:“ msg”:“错误:ValidationError:first_name:需要路径first_name。last_name:需要路径last_name。电子邮件:需要路径email。”}

// 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('Connected to database mongoDB @ 27017');
});

//on error
mongoose.connection.on('error', (err) => {
  if (err) {
    console.log('Error in DB connection' + err);
  }
});

//port no
const port = 3000;

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

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

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

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

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

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

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

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


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


//add contact
router.post('/contacts', (req, res, next) => {
    console.log(req.body)
    let newContact = new Contact({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email: req.body.email

    });

    newContact.save((err, Contact)=>{
        if (err) {
            res.json({ msg: ' Error: '+err});
        }
        else {
            res.json({ msg: 'Contact added successfully' });;
        }
    });
});

//delete 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;
const mongoose = require('mongoose');



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

const Contact = module.exports = mongoose.model('Contact', ContactSchema);
javascript node.js express mean-stack
1个回答
0
投票

req.body中显然没有值。

您能确认您寄给邮递员的尸体看起来像这样吗?

{
    "first_name": "xxx",
    "last_name": "yyy",
    "email": "zzz"
}

[将Content-Type标头设置为application/json也是非常重要的。如果您选择JSON作为格式,邮递员将自动添加它:

json

© www.soinside.com 2019 - 2024. All rights reserved.