【发布时间】:2018-05-20 16:18:15
【问题描述】:
这是我的html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node delivered HTML </title>
</head>
<body>
<div>
<h1>Send JSON to Node</h1>
<button onClick="sendJSON()">Send</button>
<p id ="result"></p>
</div>
<script>
var myData = [
{
"author": "Bill",
"title": "Chris",
"genre": "Chrisdss",
"price": 20
},
{
"author": "Bill",
"title": "Chrisss",
"genre": "Chrdsdss",
"price": 24
}
]
function sendJSON(){
console.log(myData);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML =
this.responseText;
}
};
xmlhttp.open("POST", "http://localhost:3000");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify(myData));
}
</script>
</body>
</html>
这是我的 server.js 文件
const express = require('express')
const bodyParser = require('body-parser')
const mysql = require('mysql');
const path = require('path')
const app = express()
var TABLE = 'table';
var books =[]
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "0december"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname+ '/frontend.html'));
});
app.post('/', function(req, res) {
var jsondata = req.body;
var values = [];
console.log(req.body);
for(var i=0; i< jsondata.length; i++){
values.push([jsondata[i].author,jsondata[i].title,,jsondata[i].genre,,jsondata[i].price]);
}
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
con.query('INSERT INTO table (author,title,genre,price) VALUES ?', [values], function(err,result) {
if(err) {
res.send('Error');
console.log(err);
}
else {
res.send('Success');
}
});
});
app.listen(3000, () => console.log('Books API listening on port 3000'))
我的服务器运行良好,但我尝试了很多方法,但出现 SQL 语法错误。我也尝试了 W3C 教程,但我仍然遇到同样的错误。可能是因为我的数据库修改不正确?
我的模型名为 table,它包含 id、author、title、genre、price id 是自动递增的,除了价格是浮点类型之外,所有内容都是字符串。为什么即使我的语法与教程完全相同,我也会收到语法错误?
编辑:错误是 sqlMessage: '您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在 \'table (author,title,genre,price) VALUES (\'Bill\', \'Chris\', NULL, \'Chrisdss\' 附近使用正确的语法, NULL\' 在第 1 行', sqlState: '42000', 指数:0, sql: 'INSERT INTO table (author,title,genre,price) VALUES (\'Bill\', \'Chris\', NULL, \'Chrisdss\', NULL, 20), (\'Bill\', \ 'Chrisss\', NULL, \'Chrdsdss\', NULL, 24.1)' }
【问题讨论】:
-
显示错误信息
-
table是一个糟糕的表名选择,因为它是一个保留字。您应该尝试更改表的名称或将其包装在查询中的反引号中,如下所示。INSERT INTO `table` (aut... -
是的,所以我搞砸了我的数据库是表,我的模型是书,所以我在连接中添加了
database: table并插入到books但现在我得到'列数不匹配第 1 行的值计数,
标签: mysql node.js express syntax