我是节点的新手,我无法连接到本地数据库。我已经安装了node-mysql模块和所有东西,并在我的server.js中添加了这样的路径:
var posts = require('./routes/posts');
server.get('/posts/index', posts.index);
然后我想在我的“posts / index”中访问数据库并在页面上写帖子。我是这样做的:
exports.index = function(req, res){
var mysql = require('mysql');
var connection = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '5catryws',
database: 'node_db',
});
connection.connect(function(err){
if(err){
console.log("ERROR!!! \n"+err);
throw err;
}
else
console.log('CONNECTED!!!');
});
var result;
var query = connection.query(
'SELECT * FROM posts',function(err, rows)
{
if (err) {
throw err;
}
console.log('rows', rows);
result = rows;
});
connection.end(function(err){
console.log('Connection closed!');
});
res.render('posts/index',{posts: result,title: 'TITLE'});
};
在控制台中我得到以下内容:
ERROR !!! 错误:连接ECONNREFUSED
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
--------------------
at Handshake.Sequence (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/mysql/lib/protocol/sequences/Sequence.js:15:20)
at new Handshake (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/mysql/lib/protocol/sequences/Handshake.js:9:12)
at Protocol.handshake (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/mysql/lib/protocol/Protocol.js:41:50)
at Connection.connect (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/mysql/lib/Connection.js:73:18)
at exports.index (/Users/nikola/Sites/nodejs_dummy/myapp/routes/posts.js:11:13)
at callbacks (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/express/lib/router/index.js:164:37)
at param (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/express/lib/router/index.js:138:11)
at pass (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/nikola/Sites/nodejs_dummy/myapp/node_modules/express/lib/router/index.js:33:10)
DEBUG:程序节点server.js退出,代码为8
请立即帮我解决这个问题!
THX IN ADVANCE !!!
答案 0 :(得分:1)
请检查您的mysql数据库是否在您的计算机上运行在localhost和端口3306上(默认)。
答案 1 :(得分:0)
每次调用模块时都不要创建连接。在节点始终运行的情况下,您可以在需要模块时创建数据库连接,然后在导出的任何函数中使用连接对象。如果要为每个请求创建连接,请使用PHP;)