Ignat Ospadov Ignat Ospadov - 20 days ago 12
Node.js Question

Chaining GET request with a response Node.js

I am trying to perform a GET request to an API and return the data from the API response to the client. I think the client receives a response before the GET request to the API finishes. How can I change the code to ensure that the response from the API is passed on to the client?

if (request.method == 'POST' && request.url == '/locationdata') {
var body = '';
request.on('data', function (data) {
body += data;
});

request.on('end', function () {
var formattedLocation = body.replace(/[\[\]']+/g, '');
var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation;

response.writeHead(200, { 'Content-Type': 'application/json' });
var apiData = '';

var apirequest = function () {
https.get(urlAPI, function (response) {
response.on('data', function (data) {
apiData += data;
});
response.on('end', function () {
console.log(apiData);
return apiData;
});
});
}

response.end(apirequest);
});

return;
}

Answer

You are ending the response to the client before you get all the data from the api. Moving the response.end() call up to the end of the api response should fix it:

if (request.method == 'POST' && request.url == '/locationdata') {
    var body = '';
    request.on('data', function (data) {
        body += data;
    });

    request.on('end', function () {
        var formattedLocation = body.replace(/[\[\]']+/g, '');
        var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation;

        response.writeHead(200, { 'Content-Type': 'application/json' });
        var apiData = '';

        https.get(urlAPI, function (apiResponse) {
            apiResponse.on('data', function (data) {
                apiData += data;
            });
            apiResponse.on('end', function () {
                console.log(apiData);
                // send response to browser after we get all the data from the api
                response.end(apiData);
            });
        });

        // remove this because we moved it up
        //response.end(apirequest);
    });

    return;
}