首页 > 解决方案 > 异步函数中的 HTTPS 请求 - 无数据

问题描述

抱歉,这似乎是一个愚蠢的问题,但我在 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
};

标签: javascriptnode.js

解决方案


你需要这个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);
            });
        });

    })
}

推荐阅读