how can i retrieve data from an http response from nodejs?

Without modifying your code too much, this is how you do it:

'use strict';

const { Console } = require('console');
const https = require('https');

function makeRequest(page){    
    return new Promise(resolve => {
        let obj='';
        https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
            let data ='';

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

            res.on('end',function(){
                obj=JSON.parse(data);
                resolve(obj);
            });
        });
    });
}


async function getCountryName(code) {          
    const pages = 25;
    var i = 1;  
    let f = null  
    while(i <= pages && f === null){
        console.log(i);
        const data = await makeRequest(i) // put in try/catch   
        const p = data['total_pages'];
        const search = data['data'].find(o => o.alpha3Code === code);   
        f = search !== null ? search['name'] : null;
        i++;
    }
   return res;
}

async function main() {
  const name = await getCountryName('ARG');
  console.log(`${name}\n`);
}

main();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top