当我提交表单数据时,数据添加到mysql数据库,值显示为未定义。
任何人都可以向我展示这个问题,我对NodeJs的发展很新。
HTML doc
<html>
<form method="post" action="/add">
Name : <input name="mname" type ="text" > <p>
Age : <input name="mage" type ="text" > <p>
Department : <input name="mdepartment" type="text" > <p>
City : <input name="mcity" type = "text"> <p>
<input type="submit" value ="submit">
<input type="reset" value="reset">
</form>
</center>
和我的Javascript文件如下
myapp.js
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234'
});
connection.query('USE samplenodejs');
app.set('port',3000);
app.use(bodyparser.urlencoded({extended : false}));
app.get('/', function(req, res) {
console.log('GET /');
res.sendFile(__dirname + '/AddDetails.html');
});
app.post('/add',function(req,res){
connection.query("INSERT INTO test VALUES('','"+req.body.mname+"','"+req.body.mage+"','"+req.body.mcity+"','"+req.body.mdepartment+"')",function(err,res){
if(err) throw err;
});
res.redirect('/');
});
app.listen(app.get('port'));
console.log('Express server listening on port '+app.get('port'));
答案 0 :(得分:0)
我希望您从客户端获得有效数据。以下是插入数据的功能。 Mysql字符串常量应该用"
引号括起来。
app.post('/add',function(req,res){
//Check this log in console, it should print all the values properly, if not issue is at clinet side
console.log('Input:: name='+req.body.mname+' age='+ req.body.mage +' city='+ req.body.mcity + ' dep=' + req.body.mdepartment, req.body);
var Query = `INSERT INTO test (id, name, age, city, department) VALUES ("", "${req.body.mname}","${req.body.mage}","${req.body.mcity}","${req.body.mdepartment}" )`;
//printing query in the console, if you still face the issue, you can execute this query manually.
console.log("Query :" + Query );
connection.query(Query, function(err,res){
if(err) {
console.error('Error in sql query:' + Query + ' Err', err);
throw err;
}
});
res.redirect('/');
});
您不应该将用户输入直接传递给SQL查询,总是需要进行输入验证。
在NodeJs中,最好使用JSON键:值对进行插入,如下所示 connection.query(&#39; INSERT INTO test SET?&#39;,{name:req.body.mname,age:req.body.mage},function(err,res){});