我正在創建一個node.js應用程序,它將查看傳遞給它的URL,然後返回正確的數據庫連接字符串。以下是我的genericServer.js文件。第二個代碼塊是我的Connection.js文件。當一個id在URL中傳遞到genericServer文件時,我將它傳遞給中間件connection.getConnString。如何將函數調用值存儲到變量node.js
var express = require('express');
var connection = require('./connection');
var connString = "";
var app = express();
app.get('/connectionString/:id', connection.getConnString, function(res){
res.on('response', function(response) {
res.on('data', function(chunk) {
connString += chunk;
console.log("The connection String is: " + connString);
});
});
});
app.listen(3333);
截至目前下面的代碼不會返回正確的連接信息,但我需要關閉在一個變量在(genericserver.js)服務器級別存儲這些數據。我認爲在調用connection.GetConnString中間件之後,我可以使用函數(res)捕獲genericServer.js中的響應。到目前爲止,似乎中間件進程發回了響應,但從未發生函數(res){}的回調。
有關如何在仍使用app.get()時將connection.getConnString響應存儲到genericServer調用中的變量的任何想法?
var sql = require('msnodesql');
var app = require('express');
exports.getConnString = function(req, res) {
sql.query(conn_str, "SELECT DatabaseLocation, URL FROM dbo.Hospitals WHERE URL = '" + req.params.id + "'", function(err, results) {
if (err) {
console.log("Error running query!");
console.log(err); return;
};
res.writeHead(200, {
'Content-Type': 'text/plain'
});
var connectionString = "";
switch (results[0].DatabaseLocation){
case "172.16.42.243":
connectionString = '\"Driver={SQL Server Native Client 11.0};Server=DevelopmentSQL1;Initial Catalog={' + results[0].URL + '};Database={' + results[0].URL + '};UID={userID};PWD={pssWrd};\";'
break;
case "172.16.42.244":
connectionString = '\"Driver={SQL Server Native Client 11.0};Server=DevelopmentSQL2;Initial Catalog={' + results[0].URL + '};Database={' + results[0].URL + '};UID={userID};PWD={pssWrd};\";'
break;
case "172.16.42.245":
connectionString = '\"Driver={SQL Server Native Client 11.0};Server=DevelopmentSQL3;Initial Catalog={' + results[0].URL + '};Database={' + results[0].URL + '};UID={userID};PWD={pssWrd};\";'
break;
case "172.16.42.246":
connectionString = '\"Driver={SQL Server Native Client 11.0};Server=DevelopmentSQL4;Initial Catalog={' + results[0].URL + '};Database={' + results[0].URL + '};UID={userID};PWD={pssWrd};\";'
break;
case "172.16.42.247":
connectionString = '\"Driver={SQL Server Native Client 11.0};Server=DevelopmentSQL5;Initial Catalog={' + results[0].URL + '};Database={' + results[0].URL + '};UID={userID};PWD={pssWrd};\";'
break;
}
console.log(connectionString);
res.end(connectionString);
});
};
感謝robertklep! – 2013-03-25 19:07:11