mysql - 如何使用 Node 从 MySQL 数据库中获取数据
问题描述
我是新手,正在开发一个食谱应用程序,但在显示 MySQL 数据库中的数据时遇到了问题。连接已成功创建,但是,我不确定如何访问数据。当我在终端中运行 node server.js 时,我得到“已连接”,当我访问 localhost:8080/users 时,我在终端中收到“无法访问此站点”消息:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
我有点卡在这里。有人知道解决方案或指导我一点吗?非常感谢!
服务器.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
解决方案
mysql
建立连接后,您正尝试重新连接。请参阅我对以下代码的评论
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
当您尝试解析 GET 路由时,您会尝试再次连接
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
由于您使用的是默认连接方法,因此尝试连接到已建立的连接将导致驱动程序抛出 Handshake 错误。
如果要重用连接,请将其存储在变量中,然后在代码的其他部分中重用。
如果您想改为管理多个连接,我建议您改为查看createPool
。
推荐阅读
- apache-camel - 无法让 Camel 解组 zipfile 工作?
- ruby-on-rails - 如何获取关联记录以显示在活动管理员中?
- javascript - 从 javascript 调用 Kotlin/React
- expression - 无法将函数添加到 jcl 中的表达式评估器
- heroku - heroku 管道缺少“测试”阶段选项
- javascript - 如何创建一个函数来根据位置和时间计算值?
- python - “str”对象没有属性“port”
- reactjs - 我如何检查用户是否在反应中更有效地进行身份验证?
- node.js - stomp.ack 正在产生错误:收到消息 ID 的意外 ACK
- c# - 从后面的代码中设置 UWP NavigationViewItem 图标