无法通过 Nodejs 连接到 MySQL [英] Unable to Connect to MySQL via Nodejs
问题描述
我已经安装了 Node.js,如下所示:
I have installed Node.js as below:
root@server1:~#apt-get install nodejs
然后安装npm如下:
root@server1:~#apt-get install npm
然后将 MySQL 模块安装到服务器目录中,如下所示:
Then installed the MySQL module inside the server directory as below:
root@server1:~#cd /var/www/
root@server1:/var/www# npm install mysql
下面是node.js服务器(server.js)的代码(使用正确的凭证而不是xxx):
Below is the code for node.js server (server.js) (used correct credential instead of xxx):
var mysql = require('mysql');
var db_config = {
host : 'localhost',
user : 'xxx',
password : 'xxx',
database : 'xxx'
};
var connection;
function handleDisconnect(){
connection = mysql.createConnection(db_config);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
}
else{
throw err;
}
});
}
handleDisconnect();
当我像下面这样运行 Node.js 服务器时:
When I run the Node.js server like below:
root@server1:~#node /var/www/server.js
我收到一般错误!如下:
I get general error! It is below:
error when connecting to db: { [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
fatal: true }
更新:
我能够从 PHP (Apache2) 连接到 MySQL,并且 MySQL 在我的 Ubuntu 12.04 服务器上运行良好,如下所示:
I am able to connect to MySQL from PHP (Apache2) and MySQL is working fine on my Ubuntu 12.04 server as seen below:
root@server1:~# netstat -ltnp | grep 3306
输出:
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 556/mysqld
请您建议如何解决此问题?Node.js 在不同的服务器上工作,但我不知道为什么它在这里不起作用!
Would you please advise how to resolve this issue? The Node.js is working on different server but I don't know why it is not working here!
谢谢.
推荐答案
您需要将 socket path
的值添加到 db_config
对象中:
You need to add the value of socket path
to the db_config
object:
db_config.socketPath = '/var/run/mysqld/mysqld.sock'
例如在 MAMP 中,您转到 http://localhost:8888/MAMP,您会发现:
For example in MAMP, you go to http://localhost:8888/MAMP, and you find:
/Applications/MAMP/tmp/mysql/mysql.sock
最后你有:
var connection = mysql.createConnection({
host : db_config.host,
user : db_config.user,
password : db_config.pass,
database : db_config.db,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
这篇关于无法通过 Nodejs 连接到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!