[英]NodeJS/ExpressJS send response of large amount of data in 1 stream
我正在使用本机 mongo rest api 对应用程序进行原型设计,其中 Node 返回大约 400K 的 json。 我使用以下命令向 mongo 的本机 api 请求并返回结果:
http.request(options, function(req)
{
req.on('data', function(data)
{
console.log(data,data.rows);
response.send( 200, data );
}
);
}
)
.on('error', function(error)
{
console.log('error\t',error);
response.send(500, error);
}
)
.end();
当我通过 curl 点击http://localhost:8001/api/testdata
时,响应是正确的(从console.log
输出到 Node 控制台的内容和 curl 接收到的内容)。 但是当我在我的应用程序中通过 ajax 访问它时,stream 被中断了,即使输出到 Node 控制台(终端)的data
也很奇怪:它有多个 EOF,并且 chrome 开发工具中调用的 Network > 响应首先结束EOF。
另一件奇怪的事情: data
看起来像:
{
"offset": 0,
"rows": [ … ]
}
但是在节点和客户端(角度)中,我都不能引用 data.rows (它返回未定义)。 typeof data
返回[object Object]
。
编辑curl 和 angular 的请求标头(由节点报告)是:
req.headers: {
'x-action': '',
'x-ns': 'test.headends',
'content-type': 'text/plain;charset=utf-8',
connection: 'close',
'content-length': '419585'
}
EDIT I checked response headers in both angular and curl directly (instead of from Node), annnd there's a disagreement (same output from both curl and angular directly instead of from node):
access-control-allow-headers: "Origin, X-Requested-With, Content-Type, Accept"
access-control-allow-methods: "OPTIONS,GET,POST,PUT,DELETE"
access-control-allow-origin: "*"
connection: "keep-alive"
content-length: "65401" // <---------------- too small!
content-type: "application/octet-stream"
// ^-- if i force "application/json"
// with response.json() instead of response.send() in Node,
// the client displays octets (and it takes 8s instead of 0s)
date: "Mon, 15 Jul 2013 18:36:50 GMT"
etag: ""-207110537""
x-powered-by: "Express"
Node的http.request()以块的形式返回数据以进行流式传输(如果他们明确说明这一点会很好)。 因此,有必要将每个块写入Express的响应主体, 监听http请求的结束 (实际上没有记录),然后调用response.end()
来实际完成响应。
var req = http.request(options, function(res)
{
res.on( 'data', function(chunk) { response.write(chunk); } );
res.on( 'end', function() { response.end(); } );
}
);
req.on('error', function(error) { … });
req.end();
response
是Express的响应,初始客户端请求(curl或angular的ajax调用)。
resp.set('content-type', 'application/json');
const stream = db.Country.findAllWithStream();
// console.log(stream);
stream.on('data', chunk => {
stream.pipe(resp);
});
stream.on('end', () => {
console.log('\n\nEND!!!!!');
resp.end()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.