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?
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments