为了账号安全,请及时绑定邮箱和手机立即绑定

Nodejs无法发帖

Nodejs无法发帖

森林海 2022-07-08 15:55:27
我对编程很陌生,正在按照教程学习。我被卡住了,无法使用代码发布新条目,也无法找到我在这里遗漏的内容。任何帮助将不胜感激。当我尝试使用邮递员发帖时,我收到验证错误,当我尝试获取值时,我收到 []。编辑:错误消息:“msg”:“错误:ValidationError:first_name:first_name需要路径。,last_name:last_name需要路径。,电子邮件:email需要路径。”}// importing modulesvar 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 mongoDBmongoose.connect('mongodb://localhost:27017/contactlist');//on connectionmongoose.connection.on('connected', () => {  console.log('Connected to database mongoDB @ 27017');});//on errormongoose.connection.on('error', (err) => {  if (err) {    console.log('Error in DB connection' + err);  }});//port noconst port = 3000;//adding middlewareapp.use(cors());//body - parserapp.use(bodyparser.json());//static filesapp.use(express.static(path.join(__dirname, 'public')));//routesapp.use('/api', route);//testing serverapp.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 contactrouter.get('/contacts', (req, res, next) => {    Contact.find(function (err, contacts) {        res.json(contacts);    })});//add contactrouter.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' });;        }    });});
查看完整描述

2 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

在你req.body那里显然没有价值。


你能确认你寄给邮递员的尸体是这样的吗?


{

    "first_name": "xxx",

    "last_name": "yyy",

    "email": "zzz"

}

将Content-Type标头设置为application/json. 如果您选择 JSON 作为格式,邮递员会自动添加它:

//img1.sycdn.imooc.com//62c7e31c0001162808030392.jpg

查看完整回答
反对 回复 2022-07-08
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

问题在于身体解析器的安装。


npm link body-parser


查看完整回答
反对 回复 2022-07-08
  • 2 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号