node.js - NodeJS/ExpressJS 在 1 个流中发送大量数据的响应

标签 node.js mongodb angularjs express xmlhttprequest

我正在使用原生 mongo rest api 对应用程序进行原型(prototype)设计,其中 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 访问它时,流…被中断了,甚至输出到 Node 的控制台(终端)的 data 也很奇怪:它有多个 EOF,并且 Network > 对调用的响应chrome 的开发工具在第一个 EOF 结束。

另外一件奇怪的事情:data 看起来像:

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

但是在 Node 和客户端( Angular )中,我都不能引用 data.rows(它返回未定义)。 typeof data 返回 [object Object]

EDIT curl 和 angular 的请求 header (由 Node 报告)是:

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

编辑我直接检查了 angular 和 curl 中的响应 header (而不是来自 Node),发现存在分歧(直接来自 curl 和 angular 而不是来自 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() 返回 chunks 中的数据用于流式传输(如果他们明确说明这一点会很好)。因此有必要将每个 block 写入 Express 响应的正文中,listen for the end of the http request (实际上并没有记录),然后调用 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 调用)的响应。

关于node.js - NodeJS/ExpressJS 在 1 个流中发送大量数据的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17622265/

相关文章:

mysql - 在每次迭代中运行查询

node.js - 使用 PassportJS 在 Session 中修改 user.username

Mongodb - 将嵌套文档与未知键匹配

unit-testing - angular-mock.js 与 htmlunit 冲突吗?如何在 maven-jasmine 中使用 angular-mock.js 测试 Angular 应用程序

javascript - Angular JS 意外标记

node.js - 让 Cordova/Phonegap 在 Genymotion 虚拟设备上进行仿真

mongodb - 如何将 meteor 连接到现有后端?

node.js - TypeError:无法解构 `db` 或 'undefined' 的属性 'null'

javascript - 如何将第一个和第三个字母大写?

node.js - 使用 Karma 加载 HTML 文件