问题描述
我正在尝试在Node中编写一个简单的server.js,它将来自我的html文件的表单数据发布到MySQL中.但是我收到语法错误.我将在下面发布代码和错误.我正在努力解决这个问题.
I am trying to write a simple server.js in Node, that posts form data from my html file, into MySQL. But I am getting a Syntax error. I will post the code and error below. I'm struggling to resolve this issue.
<head>
<title>Learning Node Server</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="header">
<h1>Learning Node and JS</h1>
<p>With Ninad</p>
</div>
<form action="/data" method="post">
<label for="name">Enter your name in the database</label>
<input type="text" name="name">
<input type="submit" value="submit" />
</form>
<div class="container"></div>
<script type="text/javascript" src="main.js"></script>
</body>
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//app.use(express.json());
//app.use(express.urlencoded());
//app.use(app.router);
app.use(express.static('public'));
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '3748',
database : 'nodedb'
});
connection.connect();
app.get('/', function (req, res) {
res.sendFile(__dirname + '/node.html');
});
app.post('/data', function(req, res){
var username=req.body.name;
connection.query("INSERT INTO `names` (name) SET ?", username.toString(), function(err, result){
if(err) throw err;
console.log("1 record inserted");
});
res.send(username);
});
//connection.end();
app.listen(3000, function () {
console.log('Example app listening on port 3000');
});
如果我输入yahoo2作为名称,这是我得到的错误-
If I entered yahoo2 as the name, this is the error I get-
您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以在第1行的'SET'yahoo2'附近使用正确的语法 在Query.Sequence._packetToError(/home/ninad/node-workspace/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET 'yahoo2'' at line 1 at Query.Sequence._packetToError (/home/ninad/node-workspace/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
推荐答案
应该是这个
app.post('/data', function(req, res){
var username=req.body.name;
connection.query("INSERT INTO `names` (name) VALUES (?)", username.toString(), function(err, result){
if(err) throw err;
console.log("1 record inserted");
});
res.send(username);
});
这篇关于使用带有Express的Node.js将表单数据发布到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!