nodejs http.get レスポンスの本文はどこにありますか? 質問する

nodejs http.get レスポンスの本文はどこにありますか? 質問する

http://nodejs.org/docs/v0.4.0/api/http.html#http.requestのドキュメントを読んでいますが、何らかの理由で、返された完了した応答オブジェクトの body/data 属性を実際に見つけることができないようです。

> var res = http.get({host:'www.somesite.com', path:'/'})

> res.finished
true

> res._hasBody
true

完了しました (http.get がそれを行います)。そのため、何らかのコンテンツが含まれているはずです。しかし、本体もデータもなく、読み取ることができません。本体はどこに隠れているのでしょうか?

ベストアンサー1

http.requestドキュメントには、イベント処理を通じて応答の本文を受信する方法の例が含まれていますdata

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

http.get は、自動的に呼び出されることを除いて、http.request と同じことを行いますreq.end()

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  res.on("data", function(chunk) {
    console.log("BODY: " + chunk);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

おすすめ記事