I'm new to node. I created a simple server. The idea is that at each request, this servers makes an http request to a Weather API, and when it gets the answer, it send the answer to the client. I think the server is sending the answer too fast. This is my code:
var http = require("http");
function getWeather()
{
var http2 = require("http");
http2.get("http://api.openweathermap.org/data/2.5/weather?lat=48.914348&lon=2.300282&appid=blabla123456&units=metric", (resp) => {
let data = '';
var answer = '-';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
answer += JSON.parse(data).name + ", " + JSON.parse(data).sys.country + "\n" +JSON.parse(data).main.temp + "C";
return(answer);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
function hi(){
return(5);
}
http.createServer(function (request, resp) {
resp.writeHead(200, {'Content-Type': 'text/plain'});
resp.end("Answer: " + hi() + " " + getWeather());
}).listen(8080);
console.log('Server running');
As you see, function getWeather returns answer, and function hi returns 5. My server response is "Answer: 5 undefined", so the getAnswer() return isn't presented, but the hi() return is there.
In the console, answer is printed after my server's answer, and it is exactly what I want it to show, but just too late.
Hope you can help me to solve this :)
Thanks!