我正在嘗試通過集成node.js和mysql模塊https://npmjs.org/package/mysql的快速框架來工作。我有一個簡單的應用程序設置(通過使用快速命令行),我也有一個模塊聲明爲與一些數據庫屬性一起工作。篩選Node.js,Express和mysql模塊
我的DB模塊的設置是這樣的:
app.js
node_modules
|___db
|
node_modules
|___mysql
與MySQL模塊的設置是DB模塊的依賴性。
在我index.js爲DB模塊我有一些模塊的出口設置由應用程序進行訪問:
/*
* Connection params for database
*/
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'database',
});
var connect = connection.connect(function(err){
if(!err){
console.log("You are connected to the database.");
}
else{
throw err;
}
});
var end = connection.end(function(err){
if(!err){
console.log("Mysql connection is terminated.")
}
else{
throw err;
}
});
module.exports = {
connect: connect,
connection: connection,
end: end,
}
在我app.js文件,我需要我的數據庫模塊,並指定部分航線。我也試圖使用路由功能的中間件(estDb)的app.get方法內爲客戶路線:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, clients = require('./routes/clients')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, db = require('db');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
var estDb = function(req, res, next){
db.connect;
db.connection.query("SELECT * FROM Table", function(err, results){
if(!err){
req.results = results;
}
else{
throw err;
}
});
db.end;
next();
}
app.get('/', routes.index);
app.get('/clients', estDb, clients.view);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
的問題我有 是,它似乎是我的數據庫功能(我模塊出口),當我開始爲我掙的日誌中的應用越來越被稱爲:
Express server listening on port 3000
You are connected to mysql.
Mysql connection is terminated.
不是當URL http://localhost/clients
請求(這就是我)定義爲路線。正如你所看到的,它在控制檯記錄「監聽端口3000上的Express服務器」消息後立即觸發db.connect()和db.end() - 這導致我相信它是從定製數據庫模塊我在用着。隨後,當我去的路線http://localhost/clients
我得到一個錯誤:
500 Error: Cannot enqueue Query after invoking quit.
如果我刪除從數據庫模塊connection.end()函數,我可以連接到數據庫和檢索結果;不過,如果我重新加載頁面,並嘗試再次加載結果,我得到一個錯誤:
Cannot enqueue Handshake after already enqueuing a Handshake
我不明白爲什麼我的模塊出口射擊時我啓動應用程序?我認爲這是我陷入困境的地方。
任何建議或幫助將是偉大的。
我還會看看Chris對estDb中缺少的括號提出的建議。 –
嘿赫克託,謝謝你檢查這個。你指着我正確的方向,迫使我看看我在db模塊中聲明的內容。我碰到的麻煩實際上並不是上面指出的'createConnection()'方法,而是隨後的'connect()'和'end()'方法。我認爲通過設置'connect = connection.connect()'它會將該函數存儲在變量中,但你指出它需要是'connect = function(connection){connection.connect(); }'。感謝您的建議。 – tthenne