5

ノードが約 400K の json を返すネイティブ mongo rest api を使用してアプリのプロトタイプを作成しています。以下を使用して、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 経由でヒットすると、ストリームが中断dataされ、ノードのコンソール (ターミナル) に出力されても奇妙です: 複数の EOF があり、Chrome の開発ツールでの呼び出しに対する Network > 応答は最初の EOF で終了します.

もう1つの奇妙なこと:data次のようになります:

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

しかし、ノードでもクライアント側(角度)でも data.rows を参照できません(未定義を返します)。typeof data戻ります[object Object]

EDIT curl と angular の両方のリクエスト ヘッダー (Node によって報告される) は次のとおりです。

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

EDIT私はAngularとcurlの両方で直接(Nodeからではなく)応答ヘッダーをチェックしましたが、意見の相違があります(ノードからではなく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"
4

1 に答える 1

11

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();

Expressresponseの応答は、最初のクライアント要求 (curl または angular の ajax 呼び出し) です。

于 2013-07-15T21:41:03.163 に答える