0
編輯 我的問題稍有變化,所以我正在更新我的代碼並修改我的問題。一切似乎都工作,除了我沒有看到我的瀏覽器中返回我的JSON。Node.js數據庫查詢
這裏是我當前的代碼:
'use strict';
var util = require('util');
var http = require('http');
var sql = require("mssql");
var express = require('express')
var port = process.env.PORT || 1337;
var membershipNumber;
var results;
var queryString;
var app = express();
function getParams() {
app.get('/:number', function (req, res) {
console.log("\nPARAMS:");
console.log(req.params.number);
membershipNumber = req.params.number;
queryString = util.format('SELECT major_key, status, paid_thru FROM name WHERE major_key = \'%s\' and member_record = 1', membershipNumber);
console.log("\nQUERY:");
console.log(queryString);
res.setHeader('Content-Type', 'application/json');
// res.end(queryDatabase(queryString));
res.send(queryDatabase(queryString));
});
app.listen(port);
}
function queryDatabase(query) {
var config = {
server: 'testserver',
database: 'test_db',
user: 'sa',
password: 'password',
port: 1433
};
var connection = new sql.Connection(config);
connection.connect().then(function() {
var req = new sql.Request(connection);
req.query(query).then(function (recordset) {
results = recordset;
console.log("\nRESULTS:");
console.log(results);
connection.close();
//Convert results to JSON string
var jsonString = JSON.stringify(results);
console.log("\njsonString:");
console.log(jsonString);
return jsonString;
})
.catch(function (err) {
console.log(err);
connection.close();
});
})
.catch(function (err) {
console.log(err);
});
}
getParams();
這裏是我的console.log報表控制檯」
PARAMS:
0001354648
QUERY:
SELECT major_key, status, paid_thru FROM name WHERE major_key = '0001354648' and member_record = 1
RESULTS:
[ { major_key: '0001354648',
status: 'SN',
paid_thru: 2016-10-31T00:00:00.000Z } ]
jsonString:
[{"major_key":"0001354648","status":"SN","paid_thru":"2016-10-31T00:00:00.000Z"}]
我明白了,我在我的問題中提到過。刪除appFunction()中的問題是,當我將它取出時,我沒有得到JSON字符串。 – raginggoat
抱歉。我做了一個編輯,提供了一種獲取JSON字符串的方法(請參閱帖子底部) –
tl; dr:返回'/:number'路由中的JSON字符串,而不是使用其他路由將其返回。 –