0

Sorry if this seems like a silly question but I'm having some problems with a https request. In my async JS function I'm trying to simply fetch some data from a REST api via https. In my browser and Postman I'm receiving data but I can't seem to fetch it in my request here... the res is always null. Does anyone see something wrong that I can improve or a better way of returning the requested data?

const https = require('https');

const loadData = async () => {
    const api_url = 'https://MYURL.com?apiKey=123thisismyAPIKey';
    
    let options = {
        apiKey: '123thisismyAPIKey'
    };

    let request = https.get(options,function(res,error){
        let body = '';

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

        res.on('end', function() {
            console.log(body);
        });
        res.on('error', function(e) {
            console.log(e.message);
        });
    });

    return request;
}

/**
 *
 * @param app
 * @returns {Promise<void>}
 */
module.exports = async (app) => {    
   
    let dataFromApi = await loadData();

    // res is null :(
    console.log(dataFromApi);

   // Return promise here
};
user11125394
  • 27
  • 1
  • 5

1 Answers1

-1

You need the loadData function to return a Promise, that will resolve with the body response once you have it.

const loadData = async () => {
    const api_url = 'https://MYURL.com?apiKey=123thisismyAPIKey';

    let options = {
        apiKey: '123thisismyAPIKey'
    };

    return new Promise((resolve, reject) => {
        https.get(options, function (res, error) {
            
            let body = '';

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

            res.on('end', function () {
                console.log(body);
                resolve(body);
            });

            res.on('error', function (e) {
                console.log(e.message);
                reject(e);
            });
        });

    })
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63