首页 > 解决方案 > 无法使用 Node.js 连接到 mysql (express)

问题描述

你好 Stacksoverflowers,

我在通过 Express 将 server.js 文件连接到 Mysql 时遇到问题。我已经安装了 mysql 并通过 npm 表达。

当我运行我的 server.js

它在我的控制台(MacOS 默认终端)中说的唯一内容是:“节点服务器正在运行 - 使用http://localhost:3000 ”(我没有错误)

并且我的网页也显示正确 - 浏览器中的“节点服务器正在运行 - 起始页”。

问题是他们没有说“连接到 MySQL 服务器”或“超时:错误消息”?(看#3)

// Dan k

//#1
// My codes from server.js

const express = require('express');
const mysql = require('mysql');
const hostname = "localhost:";
const port = 3000;

//#2
// create connection to DB 
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000
});

//#3
// Connect to DB
connection.connect(function(err) {
if (!err) {
console.log('Connected to the MySQL server.');
}
else if (err)
{
return console.error('Timeout: ' + err.message);
}
});


// Routing with Express
const app = express();

//#4
// Startpage (root)
app.get('/', function(request, response){
response.send('Node Server running - startpage...');
response.end();
})

connection.end();

//#5
app.listen(port, (err) => {
if(err) throw err;
console.log("node server running now - using http://"+(hostname)+ . 
(port)");
});

标签: mysqlnode.jsexpress

解决方案


我知道是什么导致了这个问题。您正在使用相同的端口号3000连接到您的 mysqlDB,同时使用相同的端口来运行您的 nodejs 应用程序。这确实会引发错误,但引发错误需要很长时间。所以这里的简单答案是您在方法中提到的端口createConnection()不正确,需要更改。此端口应该是运行 mysql DB 的端口号。从错误中可以清楚地看出您的 mysql DB 未在port 3306. 您可以查看这篇文章以确定您的 mysql DB 运行在哪个端口上。https://serverfault.com/questions/116100/how-to-check-what-port-mysql-is-running-on。下面给你一个参考。请看评论。

// create connection to DB 
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000 // You need to change this and put in the correct port number.
});

推荐阅读