0

I'm using a forEach loop to make a request to two different paths, but, although it does console.log() both bodyResponses, it gives error when trying to save it to render "index.ejs" with its value. (index.ejs is the template I wanna render):

manyPaths.forEach(function (element){
    var signature = crypto.createHmac('sha256', apiSecret).update(verb + element.path + expires).digest('hex');

    var headers = {
        'content-type' : 'application/json',
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'api-expires': expires,
        'api-key': apiKey,
        'api-signature': signature
    }; 
    const requestOptions = {
        headers: headers,
        url:'https://testnet.bitmex.com'+element.path,
        method: verb
    };
    request(requestOptions, function(error, response, bodyResponse) {
        if (error) {
            console.log(error);
        } else {
            console.log(bodyResponse);
            bodyResponse=JSON.parse(bodyResponse);
            res.render("index", {bodyResponse:bodyResponse});
        }
    });
});

it does console.log both responses, but I get this error for render():

Error: Can't set headers after they are sent.

Pedro
  • 1
  • 3

1 Answers1

0

You can respond to a HTTP request only ONCE. So in your FOR loop, the first response is sent,and the connection is closed, and when it comes to the second iteration it fails with the error you see. You have to wait for both calls to complete in parallel, and then kick of a function to send the response .

xan_z
  • 226
  • 1
  • 9