【问题标题】:Can't connect to mysql (express) with Node.js无法使用 Node.js 连接到 mysql (express)
【发布时间】: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);”行没有任何变化

标签: mysql node.js express


【解决方案1】:

我知道是什么导致了这个问题。您正在使用相同的端口号 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。下面给你一个参考。请看cmets。

// 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.
});

【讨论】:

  • 我将端口更改为 8889(在 connection = mysql.createConnection({) 中,现在我可以工作了 - 因为我的 MAMP 使用端口 8889...但是感谢@Apoorv 的解决方案
猜你喜欢
  • 2017-09-17
  • 1970-01-01
  • 2019-09-02
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 2014-11-25
相关资源
最近更新 更多