[英]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.