gpt4 book ai didi

javascript - Node.js:POST 未将数据发送到数据库

转载 作者:行者123 更新时间:2023-11-30 19:12:06 39 4
gpt4 key购买 nike

我正在尝试使用 Postman 发布数据。我正在使用 x-www-form-urlencoded 将数据发布到Local

没有显示错误。

将数据放到postman上后,在Database上只得到如下数据:

{
"createdAt": "2019-10-13T12:25:52.313Z",
"updatedAt": "2019-10-13T12:25:52.313Z",
"_id": "5da317e0e5a3df0a90308f68",
"__v": 0
}

不要理解没有收到数据库中数据的原因。任何帮助将不胜感激。

路线:

const express = require('express');
const router = express.Router();
const Contact = require('../controllers/CrmController');

router.post('/create', Contact.addNewContact );

Controller :

const mongoose = require('mongoose');
const { ContactSchema } = require('../models/CrmModel');

const Contact = mongoose.model('Contact', ContactSchema, 'contact');

exports.addNewContact = async(req, res, next) => {
try {
let newContact = new Contact(req.body);
let contact = await newContact.save();

res.send(contact);

} catch (err) {
res.status(500).json({ message: err.message });
}

next();
};

型号:

// Include MongoDB
const mongoose = require('mongoose');
// To Remove Deprication Warning from Console
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

//Define a Schema
const Schema = mongoose.Schema;

// Create Schema for The Current Model
exports.ContactSchema = new Schema({
firstName: {
type : String
},
lastName: {
type : String,
},
email: {
type : String,
},
company: {
type : String,
},
phone: {
type : Number,
},
createdAt: {
type : Date,
required: true,
default : Date.now()
},
updatedAt: {
type : Date,
required: true,
default : Date.now()
},
});

index.js:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const crmRoutes = require('./server/routes/crmRoutes');

const app = express();

app.get('/', (req, res, next) => {
res.send('Hello from Node App!');
});

app.use('/api/contact', crmRoutes);

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/crmdb', (err) => {
if(!err) {
console.log('MongoDB has connected successfully!');
} else {
console.log('The error: ' + err);
}
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(3000, (err) => {console.log("Server Has Started");});

module.export = app;

最佳答案

添加路由后,您将添加 bodyParser 中间件。这意味着只有稍后添加的路由才会有它。您需要将路由移到中间件之后。

关于javascript - Node.js:POST 未将数据发送到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363727/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com