猿问

Nodejs无法发帖

我对编程很陌生,正在按照教程学习。


我被卡住了,无法使用代码发布新条目,也无法找到我在这里遗漏的内容。任何帮助将不胜感激。


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


编辑:错误消息:“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' });;

        }

    });

});



森林海
浏览 141回答 2
2回答

慕丝7291255

在你req.body那里显然没有价值。你能确认你寄给邮递员的尸体是这样的吗?{    "first_name": "xxx",    "last_name": "yyy",    "email": "zzz"}将Content-Type标头设置为application/json. 如果您选择 JSON 作为格式,邮递员会自动添加它:

猛跑小猪

问题在于身体解析器的安装。npm link body-parser
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答