簡體   English   中英

NodeJS/ExpressJS在1 stream中發送大量數據的響應

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM