我在Node.js和Express中创建了一个Rest API。它与远程HANA数据库连接并执行一个查询。现在我想流式传输HTTP响应,以便我可以将它发送到浏览器中,而不是完全发送它,因为它是一个非常大的数据。
我尝试了一些没有输出的东西。我不知道原因。如果我使用response.send(data)将完整的响应发送到浏览器,它运行正常。但是流媒体正在发挥作用。
我在下面添加了代码段。
const express = require("express");
const APP = express();
const HANA_DB = require('hdb');
const BODY_PARSER = require("body-parser");
start();
function start() {
startServer();
initializeExpress();
APP.get("/data", function(request, response) {
var connection = HANA_DB.createClient({
host : "hostname",
port : "port",
user : "username",
password : "password"
});
connection.on('error', function (error) {
console.log("Error in database connection...");
});
connection.connect(function (error) {
if (error) {
console.log("Error in database connection...");
return;
}
var query = "SELECT * FROM TableName";
connection.exec(query, function(error, result) {
if(error) {
response.send("Getting error while fetching result...");
return;
}
//response.send(data);
var datalength = 0;
request.on('data', function(chunk) {
datalength += chunk.length;
console.log("DATA EVENT: " + datalength);
response.send(datalength);
})
.on('end', function() {
console.log("END EVENT: " + datalength);
response.send(datalength);
});
});
});
});
};
function initializeExpress() {
APP.all('/*', function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
response.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
response.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
APP.use(BODY_PARSER.json());
APP.use(BODY_PARSER.urlencoded({ extended: true }));
};
function startServer(config) {
var server = APP.listen("8081", function(error) {
if(error) {
console.log("Unable to connect to 127.0.0.1:8081");
return;
}
console.log("Server is listening at - 127.0.0.1:8081");
});
};
问题出在这里request.on('data',
。 request
指的是浏览器请求。
你不能使用.exec()
的流,因为exec
的回调函数是以行作为参数调用的。
要使用streaming,请使用.execute()
方法,该方法将结果集传递给回调函数。
我从来没用过hdb
,所以我不能给代码使用。
我认为你使用的逻辑对于数据流是错误的。
使用res.write而不是res.send,您还必须从数据库中读取流数据而不是一次connection.exec
我给你一个示例代码,你可以在Expressjs中了解流数据。
var http = require( 'http' );
http.createServer( function ( req, res ) {
res.writeHead( 200, {
'Content-Type': 'text/plain; charset=utf-8',
'Transfer-Encoding': 'chunked',
'X-Content-Type-Options': 'nosniff'
} );
res.write( 'Beginning\n' );
var count = 10;
var io = setInterval( function () {
res.write( 'Doing ' + count.toString() + '\n' );
count--;
if ( count === 0 ) {
res.end( 'Finished\n' );
clearInterval( io );
}
}, 1000 );
} ).listen( 8000 );