繁体   English   中英

使用 mongoose 在 express.JS 中发送 post 请求,数据未保存在数据库中

[英]sending an post request in express.JS using mongoose ,data is not saving in the database

我的 HTML 代码

<body>
    <form action="/contact" method="POST" id="contact">
        <div class="form">
            <div><input type="text" name="myname" placeholder="Type your name" required></div>
            <div><input type="text" name="city" placeholder="City" required></div>
            <div><input type="number" name="number" placeholder="Type your phone number" required></div>
            <div><input type="email" name="email" placeholder="ex:mohd53635@gmail.com" required></div>
            <div><input type="number" name="age" placeholder="Age" min="17" max="40" required></div>
            <div> Male<input type="radio" name="gender" id="male">Female <input type="radio" name="gender" id="female"></div>
            <button>Submit</button>
            <button type="reset">Reset</button>
        </div>
    </form>
</body>

使用 mongoose 发送发布请求,但数据未保存在数据库中我什至没有收到错误...

JavaScript 模块:-

const mongoose = require('mongoose');
const { ejson } = require("ejs");
const express = require("express");
const app = express();
const path = require('path')
const fs = require("fs");
const bodyParser = require("body-parser")
const { urlencoded } = require("express");
const port = 5000;
const hostname = '127.0.0.1';

//中间件

app.use('/static', express.static(path.join(__dirname, "../static")));
app.use('/static', express.static('static'))
app.use(express.static(__dirname + '/static'));

//HTTP GET 请求:-

app.get('/index.html', function(req, res) {
    res.status(200).render(__dirname + '/index.html');
})
app.get('/contact.html', function(req, res) {
    res.sendFile(__dirname + '/contact.html')
});
app.engine('html', require('ejs').renderFile);

//服务器

app.listen(port, () => {
    // console.log(`The Server Has Been Started On Port ${port}`)
});

//MongoDb Mongoose

mongoose.connect('mongodb://localhost/moonform', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true 
});
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("We are connected");

//猫鼬模式:-

const moonSchema = new mongoose.Schema({
    myname: String,
    number: Number,
    email: String,
    city: String,
    age: Number,
    gender: String
});

//猫鼬Model

let moon = mongoose.model('moon', moonSchema);

//发布请求

app.post('/contact', (req, res) => {
    let myData = new moon(req.body)
    myData.save().then((err, myData) => {
            res.send("This item has been saved to the database")
        })
        .catch(() => {
            res.status(400).send("item was not saved to the databse")
        });
});

//猫鼬查找

moon.find({ name: "moonform" }, function(err, myData) {
    if (err) return console.error(err);
    console.log(moon)
});

好的。 试试这个。

//don't forget to wrap this inside async function
const result=await moon.find({});
console.log(result)

如果这仍然给出错误,则意味着您的req.body可能为空

好吧,我终于弄清楚了我的问题,即代码中唯一缺少的东西是..

app.use(express.urlencoded());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM