2

I need to make an http request from one server to another server.

The server that will handle this request will just return a JSON Array of objects:

app.get('/array', function (req, res) {
  console.log('GET request received!');
  var response_array = [
    {
      value: 1234
    },
    {
      value: 1234
    },
    {
      value: 55
    }
  ];

  res.send(response_array);
});

I am using q-io to send the http request to that GET method /array and obtain the array:

var _getArray = function(externalUrl) {
  var request = {
    method: "GET",
    url: externalUrl
  };

  return HTTP.request(request)
    .then(function(response) {
      // I need to return the Array inside the body (a Promise) to
      // iterate on it later
      return response.body.read(); // but .read() returns a Buffer
    });
}

Both servers work right, as the request is correctly sent and received from one to another, and also the response.

The issue I have is that I am not achieving to obtain the JSON Array - as read() returns a Buffer and just response.body doesn't return the Array (as the docs say, it returns a representation of a readable stream)... how can I handle this properly to obtain the Array correctly with Promises?

charliebrownie
  • 5,777
  • 10
  • 35
  • 55
  • I think you don't need to read(), just use `return response.body` – Zohaib Ijaz Jan 28 '16 at 18:59
  • @ZohaibIjaz no, that doesn't return the Array, it returns the [body Object](http://documentup.com/kriskowal/q-io#body) which as the docs say, it is **a representation of a readable stream, either for the content of a request or a response. It is implemented as a Q-IO reader.** – charliebrownie Jan 28 '16 at 19:04
  • 1
    You'll probably have to `.read().then(JSON.parse)` – Bergi Jan 28 '16 at 19:32
  • @Bergi thank you, that was actually what I was looking for, but didn't realize I could put it that way! Post an answer and I'll mark it as correct. – charliebrownie Jan 28 '16 at 19:37
  • I wasn't sure whether it's working because you said it's a promise for a *buffer*, not a string. But maybe it gets casted just fine... – Bergi Jan 28 '16 at 19:40
  • yeah, the docs about `read()` say so: **returns a promise for the entire body as a string or a buffer.**! thank you! – charliebrownie Jan 28 '16 at 19:42

2 Answers2

2

If you can get a promise for the body content of the response, you can get a promise for the JSON payload from that by passing it through JSON.parse:

return HTTP.request(request)
  .then(function(response) { return response.body.read() })
  .then(JSON.parse);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

from the docs, https://github.com/kriskowal/q-io#body

it seems that you have to use forEach to get all items

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60