首页 > 解决方案 > 如何使用 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}/`);
});

标签: mysqlnode.js

解决方案


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


推荐阅读