mysql - 无法使用 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)");
});
解决方案
我知道是什么导致了这个问题。您正在使用相同的端口号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.
});
推荐阅读
- reactjs - 在同一个远程托管面板上从反应前端与 ASP.NET Core Web API 进行通信
- python - Python 中的矩阵使用 Numpy Python 给出错误的结果
- python - 循环读取 XML 文件最终会导致内存错误
- c++ - 井字游戏找到匹配符号和获胜者的更好方法?
- c - 条件跳转或移动取决于带问号的未初始化值
- python - Keras 模型多输入 - 类型错误:('关键字参数不理解:','输入')
- jenkins - 使用具有不同参数的定期构建选项构建 Jenkins 作业
- javascript - 在对象字面量中使用 __proto__
- ios - Swift:打印到任何类型的控制台可变参数
- amazon-web-services - 亚马逊EC2 | CodeDeploy [React] - 部署成功但未填充构建文件夹