mysql - 如何使用 Node 从 MySQL 数据库获取数据

标签 mysql node.js

我是 React 新手,正在开发一个菜谱应用程序,在显示 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

由于您使用的是默认连接方法,尝试连接到已建立的连接将导致驱动程序抛出握手错误。

如果您想重新使用连接,请将其存储在变量中,然后在代码的其他部分中重新使用它。

如果您想管理多个连接,我建议您查看createPool

关于mysql - 如何使用 Node 从 MySQL 数据库获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599238/

相关文章:

PHP 和 MySQL : Preventing attacks - What's the different between these functions?

node.js - Windows 10安装serverless后命令提示符无法运行 "serverless"

php - 找不到列 : 1054 Unknown column 'users.blog_id' :SQL: select * from `users` where `users` .`blog_id` = 1 and `users` .`blog_id` is not null

php - 根据日期显示 5 个数据库条目

MySQL 分区修剪 PARTITION BY LIST

node.js - 通过 IP 地址进行的 Socket.io 连接无法正常工作

node.js - 当我的代码不在堆栈跟踪中时,如何调试 node.js 错误?

mysql 删除标题中带有单引号的数据库

c++ - 如何调试nodejs的二进制模块?

node.js - 在多个 Node 实例中使用 Pub-Sub 进行广播