在我的节点应用程序中,我试图将数据插入到mysql数据库中。我正在学习本教程
“http://www.tutorialindustry.com/node-js-mysql-tutorial-for-beginners”
我的代码:
var express = require('express')
, http = require('http')
, mysql = require('mysql')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3002);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function( req, res) {
res.render('index');
});
//connect to mysql database
/*var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'root',
database : 'nodejsmysql'
});
connection.connect();*/
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'nodejsmysql',
debug : true,
})
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
app.get('/users', function (req, res) {
connection.query('select * from nodejs', function(err, docs) {
res.render('users', {users: docs});
});
});
// Add a new User
app.get("/users/new", function (req, res) {
res.render("new");
});
// Save the Newly created User
app.post("/users", function (req, res) {
var fname=req.body.fname;
var lname=req.body.lname;
console.log("qqqqqqqqqq")
connection.query('INSERT INTO nodejs (fname, lname) VALUES (? , ?);' , [fname, lname], function(err, docs) {
if (err) res.json(err);
res.redirect('users');
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
不会抛出任何错误。但数据不会进入数据库。
答案 0 :(得分:0)
由于您正在使用的教程的格式设置存在问题。具体而言,对于views/new.jade
文件,某些缩进是必需,否则表单将不会被提交。查看以下模板的用途:
h1 Add new User
form(method="POST" , action="/users")
p FirstName:
input#title(type="text" , name="fname")
p LastName:
input#body(type="text" , name="lname")
p: button(type="submit") Add New User
查看/ index.jade:
extends layout
block content
p Welcome to nodejs mysql tutorial
p
a(href='/users') Show All users
查看/ users.jade:
h1 Showing All Users
ul
- each user in users
li User FirstName: #{user.fname}
li User LastName: #{user.lname}
hr
a(href="users/new") Add New User
br
a(href="/") Home
如果您想了解更多信息,Jade website似乎有一些有用的信息/教程。