javascript - 异步函数中的 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
};
解决方案
你需要这个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);
});
});
})
}
推荐阅读
- java - 如何使用 Apache Camel SFTP 提取满足条件的文件(比如在特定日期之后提取文件)
- apache-kafka - Quarkus DLQ 失败策略后如何在 Kafka 消息上保留自定义标头?
- curl - 如何获取最后一个完整的 HTTP 响应,包括带有 CURL 的标头
- vba - 天气 API 错误:运行时错误“91”:对象变量...未设置
- rdf - 有没有办法在 OWL 中表达析取对象属性断言?
- angular - 订阅方法在 ngbModal 中抛出 ExpressionChangedAfterItHasBeenCheckedError 错误
- python - 如何检查网站是否有 OLV(在线视频)广告?
- c++11 - 使用 Boost 库的 TCP 类
- android - 在 Ionic Cordova 平台插件 exitApp() 之后总是 RESULT_CANCELED
- pyspark - 在 pyspark 中更改列名