我正在尝试将基本表单插入我的数据库以了解 Node 的工作原理,但我不断返回一个有趣的小错误..
error when connecting to db: { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }
我有一个用于断开连接的包装器,但这似乎也没有帮助。
SELECT * FROM player
在 mysql
中也没有返回任何内容,因此没有插入任何内容。
这是我的 server.js 文件:(当然我省略了连接凭据)
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();
app.use(express.static(__dirname));
app.use(express.json());
app.use(express.urlencoded());
app.post("/post",function(req,res) {
console.log(JSON.stringify(req.body));
res.send("Username is: "+req.body.user+".");
var post = {
name:req.body.user,
password:"testing",
email:"fake@email.com"
};
connection.query("INSERT INTO player VALUES ?",post,function(err,result) {
console.log(err);
console.log(result);
});
});
app.listen(80, function() {
console.log("Server running on port 80");
});
为什么我的连接被切断?
最佳答案
添加
con.connect();
在 app.listen(80...
之前应该可以解决问题。
关于javascript - Node.js Mysql 连接终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22165475/