Ihor Ost Ihor Ost - 6 months ago 19
Node.js Question

Printing API data (JSON) on page in NodeJS weather app

I'm creating a weather app using NodeJS.
Get json formated data from weather site api. But dont understand how can i send it to the app.

here is my code:



var http = require('http');

http.createServer (function (request, response){
response.writeHead(200, {'Content-Type': 'text/html'});
response.end();
}).listen(3000);

var getUrl = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=1111111111';

http.get(getUrl, function(res){
var body = '';

res.on('data', function(chunk){
body += chunk;
});

res.on('end', function(){
var response = JSON.parse(body);
console.log("Got a response: ", response.coord.lon);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});




Answer

The simplest way to transform your example into working code would be to put the response.end() call inside your "getUrl"'s "onEnd" block:

var http = require('http');

http.createServer (function (request, response){

    response.writeHead(200, {'Content-Type': 'text/html'});

    var getUrl = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=1111111111';

    http.get(getUrl, function(res){

        var body = '';

        res.on('data', function(chunk){
            body += chunk;
        });

        res.on('end', function(){

            var data = JSON.parse(body);
            console.log("Got a response: ", data.coord.lon);

            response.end(JSON.stringify(data)); // ENDING/SENDING RESPONSE AFTER FETCHING URL IS DONE

        });
    }).on('error', function(e){
          console.log("Got an error: ", e);
    });
}).listen(3000);

The main issue here being that the createServer callback will fire every time someone tries to access your webpage, and your "getUrl" logic is outside of that, thus wouldn't run on every request. Now that it's inside the server callback, it will. If you intend to add more functionality to this code, consider abstracting this "getUrl" functionality, but still call it from within the server callback.