Donde está body en un http nodejs.obtener respuesta?


Estoy leyendo los documentos en http://nodejs.org/docs/v0.4.0/api/http.html#http.request , pero por alguna razón, no puedo encontrar realmente el atributo body/data en el objeto de respuesta terminado devuelto.

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

> res.finished
true

> res._hasBody
true

Está terminado (http.get hace eso por ti), por lo que debería tener algún tipo de contenido. Pero no hay cuerpo, ni datos, y no puedo leer de ellos. ¿Dónde se esconde el cuerpo?

 155
Author: mikemaccana, 2011-08-06

9 answers

Http.request docs contiene un ejemplo de cómo recibir el cuerpo de la respuesta a través del manejo de data evento:

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 hace lo mismo que http.request except llama req.end() automáticamente.

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);
});
 152
Author: yojimbo87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-06 18:09:13

También quiero agregar que el http.ClientResponse devuelto por http.get() tiene un evento end, así que aquí hay otra forma en que recibo la respuesta corporal:

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

http.get(options, function(res) {
  var body = '';
  res.on('data', function(chunk) {
    body += chunk;
  });
  res.on('end', function() {
    console.log(body);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
}); 
 120
Author: bizi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-22 10:49:01

Editar: responder a sí mismo 6 años después

El await keyword es la mejor manera de manejar esto, evitando devoluciones de llamada y .then()

También necesitará usar un cliente HTTP que devuelva Promesas. http.get() todavía devuelve un objeto de solicitud, por lo que no funcionará. Podría usar fetch, pero superagent es un cliente HTTP maduro que cuenta con valores predeterminados más razonables, incluida la codificación de cadena de consulta más simple, utilizando correctamente tipos mime, JSON por defecto y otros Características del cliente HTTP. await esperará hasta que la Promesa tenga un valor-en este caso, una respuesta HTTP!

const superagent = require('superagent');

(async function(){
  const response = await superagent.get('https://www.google.com')
  console.log(response.text)
})();

Usando await, control simplemente pasa a la siguiente línea una vez que la promesa devuelta por superagent.get() tiene un valor.

 49
Author: mikemaccana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-16 09:51:07

Si desea utilizar .puedes hacerlo así

http.get(url, function(res){
    res.setEncoding('utf8');
    res.on('data', function(chunk){
        console.log(chunk);
    });

});
 11
Author: user969714,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-24 09:53:30

Necesita agregar un receptor al nodo request because.js funciona asíncrono así:

request.on('response', function (response) {
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
 });
});
 5
Author: Skomski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-06 18:29:45

El evento data se dispara varias veces con 'trozos' del cuerpo a medida que se descargan y un evento end cuando todos los trozos se han descargado.

Con el nodo soportando Promesas ahora, he creado un envoltorio simple para devolver los trozos concatenados a través de una Promesa:

const httpGet = url => {
  return new Promise((resolve, reject) => {
    http.get(url, res => {
      res.setEncoding('utf8');
      let body = ''; 
      res.on('data', chunk => body += chunk);
      res.on('end', () => resolve(body));
    }).on('error', reject);
  });
};

Puede llamarla desde una función asincrónica con:

const body = await httpGet('http://www.somesite.com');
 4
Author: nkron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 04:42:14

El módulo de aguja también es bueno, aquí hay un ejemplo que usa needle el módulo

var needle = require('needle');

needle.get('http://www.google.com', function(error, response) {
  if (!error && response.statusCode == 200)
    console.log(response.body);
});
 1
Author: Thulasiram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 13:08:52

No puede obtener el cuerpo de la respuesta del valor devuelto de http.get().

http.get() no devuelve un objeto de respuesta. Devuelve el objeto request (http.clientRequest). Por lo tanto, no hay ninguna manera de obtener el cuerpo de la respuesta del valor devuelto de http.get().

Sé que es una vieja pregunta, pero leer la documentación a la que enlazaste muestra que este fue el caso incluso cuando la publicaste.

 1
Author: Vince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-06 09:22:59

Una porción de café aquí:

# My little helper
read_buffer = (buffer, callback) ->
  data = ''
  buffer.on 'readable', -> data += buffer.read().toString()
  buffer.on 'end', -> callback data

# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
  read_buffer res, (response) ->
    # Do some things with your response
    # but don't do that exactly :D
    eval(CoffeeScript.compile response, bare: true)

Y compilado

var read_buffer;

read_buffer = function(buffer, callback) {
  var data;
  data = '';
  buffer.on('readable', function() {
    return data += buffer.read().toString();
  });
  return buffer.on('end', function() {
    return callback(data);
  });
};

http.get('http://i.want.some/stuff', function(res) {
  return read_buffer(res, function(response) {
    return eval(CoffeeScript.compile(response, {
      bare: true
    }));
  });
});
 0
Author: 18augst,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-15 14:44:07