【发布时间】: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