【发布时间】:2019-08-07 22:30:44
【问题描述】:
你好 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)");
});
【问题讨论】:
-
我假设您提到的数据库详细信息不适合隐私。例如。端口号不能与运行应用程序的端口相同。即使这样,您也应该通过错误回调得到错误。唯一可能导致上述行为的情况是
return console.error('Timeout: ' + err.message);行中的 return 语句。您能否检查您的代码并确认返回语句不是导致问题的语句。尝试将其从声明中删除console.error('Timeout: ' + err.message); -
@Apoorv 感谢您的回复 - 如果我删除或评论端口:3000 (const connection = mysql.createConnection) 此错误消息来了。错误:在 TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14) 处连接 ECONNREFUSED 127.0.0.1:3306 --------------------
-
我试过删除“return console.error('Timeout: ' + err.message);”行没有任何变化