我对编程很陌生,正在按照教程学习。
我被卡住了,无法使用代码发布新条目,也无法找到我在这里遗漏的内容。任何帮助将不胜感激。
当我尝试使用邮递员发帖时,我收到验证错误,当我尝试获取值时,我收到 []。
编辑:错误消息:“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' });;
}
});
});
慕丝7291255
猛跑小猪
相关分类