NodeJS / ExpressJS在1个stream中发送大量数据的响应

我正在使用原生mongo rest api来创build应用程序,其中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输出到节点的控制台以及curl收到的是什么)。 但是当我通过应用程序中的ajax打开它时,stream被中断了,即使输出到Node的控制台(Terminal)的数据也很奇怪:它具有多个EOF,并且chrome开发工具中的Network> response响应结束于第一个EOF。

另一个奇怪的事情是: data看起来像:

 { "offset": 0, "rows": [ … ] } 

但在节点和客户端(angular)都不能引用data.rows(它返回undefined)。 typeof data返回[object Object]

编辑 curl和angular(由Node报告)的请求标头是:

 req.headers: { 'x-action': '', 'x-ns': 'test.headends', 'content-type': 'text/plain;charset=utf-8', connection: 'close', 'content-length': '419585' } 

编辑我检查了angular度和curl直接(而不是从节点)响应头,宣布有一个不同意(从curl和angular度直接而不是从节点相同的输出):

 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" 

节点的http.request()以stream的方式返回数据块 (如果明确声明的话,会很好)。 因此,有必要将每个块写入Express的响应主体, 监听http请求的结尾 (没有真正logging),然后调用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调用)。