How to print object in Node JS

前端 未结 6 2038
忘掉有多难
忘掉有多难 2020-12-18 22:49

In the below code (running on Node JS) I am trying to print an object obtained from an external API using JSON.stringify which results in an error:

6条回答
  •  死守一世寂寞
    2020-12-18 23:44

    You do not actually get data in res. You need on('data') and on.('end')

    body is a string. It gets append on data received, so on complete you will need to parse data into json

    http.get("http://ip-api.com/json", function(res) {
        var body = '';
        res.on('data', function(data){
            body = body + data;
        });
    
        res.on('end', function() {
            var parsed = {};  
            try{
                parsed = JSON.parse(body); // i have checked its working correctly
            }
            catch(er){
                //do nothing it is already json
            }
            console.log(parsed.country);
        });
    });
    

    Noe from parsed which is a json object, you can get any property

提交回复
热议问题