我偶然发现了一个关于我的Node.JS REST API的一个非常奇怪的问题。它的目标是将HTTP请求转换为SQL请求,并将SQL响应转换为HTTP响应,这样我就可以通过SSL / TLS传输所有内容并对其进行编码。
问题在于,当响应大小很小时,一切正常,但是当它超过一定大小(大约255.37 KB)时,响应主体会在JSON中间被切断。经过多次测试后,问题似乎与HTTP响应总大小(包括标题)有关,因为当删除某些自定义标题时,会发送更多正文。我在PHP中编写了类似的代码,并且PHP API中的JSON响应很好,所以我认为问题源于Node.JS Web服务器中的错误。此外,Content-Lenght标头很好并且具有正确的值(就像PHP API响应一样)。
我使用Node.JS v6.11.0和最新版本的Express。由于npm,我的所有依赖都是最新的。
这是处理GET HTTP请求并继续执行SELECT SQL请求的函数的代码,然后解析为json字符串的答案
function SelectData(connection){
return function (req, res) {
let tableName = req.params.table;
let id = req.params.id;
console.log("GET request received with tableName = " + tableName + " and id = " + id);
// Should match this regex
if (!tableName.match(/^[\-\_\s0-9A-Za-z]+$/)){
console.log("Error: Invalid table name provided : " + tableName);
badRequestError(req, res);
return;
}
if (id !== undefined){
if (!id.match(/^[0-9]+$/)){
console.log("Error: Invalid id provided : " + id + " (table name was valid : " + tableName + ")");
badRequestError(req, res);
return;
}
}
// if id is empty, then don't use any condition, else, add SQL condition
idPart = (id == undefined) ? "" : ('WHERE id="' + id + '"');
// TODO: try to replace " + var + " by question marks and bind params, find a way to do it w/ id
connection.query("SELECT * FROM " + tableName + " " + idPart + ";", function(err, result){
res.setHeader('Content-Type', 'application/json');
console.log("Request executed successfully !");
// Works too but I prefer the .send() method
// res.status(200).write(JSON.stringify(result)).end();
res.status(200).send(JSON.stringify(result));
req.connection.destroy();
return;
});
}
}
function badRequestError(req, res){
res.setHeader('Content-Type', 'text/plain');
res.status(400).send("Bad Request");
req.connection.destroy();
}
exports.SelectData = SelectData;

编辑:昨天研究后我发现使用HTTPS模块导致了类似的问题,所以我将其删除但仍然会发生。