【问题标题】:HTTPS Request in Async function - no data异步函数中的 HTTPS 请求 - 无数据
【发布时间】:2021-08-10 17:29:36
【问题描述】:

抱歉,这似乎是一个愚蠢的问题,但我在 https 请求时遇到了一些问题。 在我的异步 JS 函数中,我试图通过 https 简单地从 REST api 获取一些数据。在我的浏览器和邮递员中,我正在接收数据,但我似乎无法在我的请求中获取它...... res 始终为空。有没有人看到我可以改进的错误或返回请求数据的更好方法?

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
};

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您需要 loadData 函数来返回一个 Promise,一旦您拥有它,它将通过 body 响应解决。

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);
            });
        });

    })
}

【讨论】:

  • 你没有在任何地方使用 api_url。
  • OP 也不是。我让他们随意放置 URL。但这是一个细节,这不是重点。关键是,loadData 必须返回一个 Promise。
  • 感谢您指出我没有返回承诺,也没有使用 URL...我会修复它并让您知道
猜你喜欢
  • 2019-01-27
  • 2011-10-13
  • 2017-06-01
  • 2021-03-31
  • 1970-01-01
  • 2018-01-17
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多