我最近一直在为express.js工作,我正面临这个问题。这是我的代码
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var app = express();
var mongoose = require('mongoose');
var option = {
server: {
socketOptions: {
keepAlive: 300000,
connectTimeoutMS: 30000
}
},
replset: {
socketOptions: {
keepAlive: 300000,
connectTimeoutMS: 30000
}
}
};
mongoose.connect('mongodb://localhost:27017/person', option).then(function(){
console.log("sucess");
}, function(err) {
console.log("error");
});
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.set('view engine', 'pug');
app.set('views', './views');
// for parsing application/json
app.use(bodyParser.json());
// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true }));
//form-urlencoded
// for parsing multipart/form-data
//app.use(upload.array());
//app.use(express.static('./public'));
// app.post('/', function(req, res){
// console.log(req.body);
// res.send("recieved your request!");
// });
app.get('/person', function(req, res){
console.log("in gettttttttttttttt")
res.render('person');
});
app.post('/person', function(req, res){
console.log("in post");
var personInfo = req.body; //Get the parsed information
if(!personInfo.name || !personInfo.age || !personInfo.nationality){
res.render('show_message', {
message: "Sorry, you provided worng info", type: "error"});
} else {
var newPerson = new Person({
name: personInfo.name,
age: personInfo.age,
nationality: personInfo.nationality
});
newPerson.save(function(err, Person){
if(err)
res.render('show_message', {message: "Database error", type: "error"});
else
res.render('show_message', {
message: "New person added", type: "success", person: personInfo});
});
}
});
app.listen(3000);
成功获取电话会在UI上呈现表单,但是当我提交表单时,发布不起作用。 这是帕格表单文件
html
head
title Person
body
form(action = "/person", method = "POST")
div
label(for = "name") Name:
input(name = "name")
br
div
label(for = "age") Age:
input(name = "age")
br
div
label(for = "nationality") Nationality:
input(name = "nationality")
br
button(type = "submit") Create new person
与mongodb的连接成功。
当我点击提交按钮时,控制台在调试模式下没有显示任何错误。 请指导!!