我从SQL Server得到一个值。之后,我尝试向用户提供一个文本文件下载,其内容是我从数据库检索到的值。我通过查询字符串传递ID值(http://localhost:8080/index.js?ID=1)。
不能在底部用数据库值设置文本变量。在这种情况下,如何将数据库值导出为文本文件?
const http = require('http');
const url = require('url');
const sql = require('mssql');
// config info database
const config = {
user: 'test_user',
password: '123',
server: 'localhost',
database: 'TestDatabase',
port: 1433,
trustServerCertificate: true,
};
http.createServer(function (req, res) {
const queryObject = url.parse(req.url, true).query.ID;
// connect to database
sql.connect(config, function (err) {
if (err) console.log(err);
// create a new Request object
let sqlRequest = new sql.Request();
// query the database and get data in the data Object
let sqlQuery='SELECT Testvalue FROM TestDatabase.dbo.TestTable WHERE ID = ' + queryObject;
sqlRequest.query(sqlQuery, function (err, data) {
if (err) console.log(err)
// display the data in the console
//console.table(data.recordset[0].Testvalue);
text = "This is a content of a txt file. Value from database = " + data.recordset[0].Testvalue;
// close the connection
sql.close();
});
});
text = 'how do I get the value in here from the database??';
res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'});
res.end(text);
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
在我看来,你只需要将你的res.writeHead... and res.end...
移动到代码块中,你从数据库中获得文本-尝试在sql.close();
之后这是假设你的sql工作。