我有 2 台服务器,一台运行前端代码(Node.js、express),另一台使用 PHPMyAdmin 运行 MySQL,两台服务器都独立工作,我可以确认 MySQL 数据库正在 3306 上运行,但每当我尝试通过 Node.js 连接时。在使用 Node.js (下面的代码)时,我收到连接拒绝错误。
const conn = mysql.createConnection({
host: '192.168.1.250',
user: 'mcd',
password: '**********',
database: 'mcd'
})
conn.connect(function(err) {
if (err) throw err;
})
我用于主机的IP地址是MySQL服务器的IP地址。所以不确定为什么它无法连接,因为它在默认端口上运行。
这是我与 Node.js 的连接:
pool = mysql.createPool({host:"localhost"
,port:"3306"
,database:"db_name"
,user:"user_name"
,password:"password_for_user"
,timezone:"utc"
,multipleStatements:true
,max:1000
,min:1
,idleTimeoutMillis:defs.QUERY_TIMEOUT});
if ( pool && pool.getConnection ) {
pool.getConnection(function(errsts, conn) {
var resp = {};
if ( errsts ) {
resp['error'] = errsts;
return;
}
resp['state'] = "connected";
if ( cbRoutine ) {
cbRoutine(conn, resp, objParams);
if ( conn != undefined ) {
conn.release();
}
}
});
}
localhost 对于我的用法来说是正确的,您应该将其替换为您的名称或 IP 地址。 defs.QUERY_TIMEOUT 在我的源代码中定义为:
var QUERY_TIMEOUT = 10 * 1000;
在我的代码中cbRoutine是一个回调函数,作为参数传入以在成功连接时调用。
请检查您是否已启动mysql端口:3306
ECONNREFUSED
错误表明它无法连接到该函数的托管位置(在本例中为 localhost)
dbConnection.js
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10, // default = 10
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dname'
});
module.exports = connection;