简体   繁体   中英

Server in nodejs, http request

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!

Because this event takes time to process, you cannot return it. Try using a callback instead!

function getWeather(callback)
    {
        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";
                callback(answer);
            });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
        });
    }

Then for the http request

http.createServer(function (request, resp) {
        resp.writeHead(200, {'Content-Type': 'text/plain'});
        getWeather(function(data) {
            resp.end("Answer: " + hi() + " " + data);
        });
    }).listen(8080);

If you can't tell, this works by calling a function that is sent when the data is ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM