我在节点9.4.0上。我尝试按照youtube上的教程 - Traversy media(https://www.youtube.com/watch?v=xrxDk1zLKdc)。我在教程中做了一切来解析由pug制作的html表单的数据,并将表单数据保存在mongoDB表中。这就是我做的。
//initailize
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/nodekb');
let db = mongoose.connection;
*********************************************
//check connection
db.once('open', function(){
console.log('Connected to Mongodb');
});
//check for db error
db.on('error',function(err){
console.log(err);
});
//init app
const app = express();
// bring in models
let Article=require('./models/article');
//load view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','pug');
//app.set('view engine','php');
//
//Body parser
app.set(bodyParser.urlencoded({extended: false}));
//parse application/json
app.use(bodyParser.json());
//home route
app.get('/',function(req,res){
Article.find({},function(err,articles){
if(err){
console.log('error');
}
else
{
res.render('index.pug',{
title:'articles',
allarticles: articles
});
}
})
//res.send('Hello world');
});
//a route to another resource
app.get('/articles/add',function(req,res){
res.render('add_article.pug',{
title:'Add articles'
});
});
// Add submit POST route
app.post('/articles/add',function(req,res){
let article = new Article();
article.title = req.body.title;//we need to install and include body-parser to parse form html body
article.author = req.body.author;
article.body = req.body.body;
article.save(function(err){
if(err){
console.log(err);
return;
}
else {
res.redirect('/');
}
});
//console.log('Submitted');
//return;
});
app.listen('3000',function(){
console.log('server started on port 3000');
});
extends layout
doctype html
html
head
title node app with express framework
body
h2 #{title}
form(method='POST', action='/articles/add')
#form-group
label Title:
input.form-control(name='title', type='text')
#form-group
label Author:
input.form-control(name='author', type='text')
#form-group
label Body:
textarea.form-control(name='body')
input.btn.btn-primary(type='submit', value='submit')
每次填写数据并提交时,数据库都会增加1但空白记录。由于某种原因,数据没有到达数据库,但它实际上增加了一个空白记录。