node.js - Nodejs https 函数需要等待 url json 响应并将其传递回调用 express 模块作为响应以在客户端打印
问题描述
我正在尝试使用 nodejs express 模块托管服务器,当它受到客户端的点击时,https 模块将尝试点击另一个 URL 并获取 json 响应保存它并将此响应提供回客户端作为对其的响应打 。PFB 我的代码旨在能够在服务器端打印响应但不能在客户端打印,PFb 我的代码使用它可以在服务器端打印响应,但不能在客户端打印。我尝试了以下评论的方式,但得到了空答案。我打算用curl打快递
const express = require('express')
const app = express()
const port = 3000
var url = require('url');
var https = require('https');
var HttpsProxyAgent = require('https-proxy-agent')
var responsedata = "";
function delay() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(42);
}, 10000);
});
}
app.get('/', async (request, response) => {
// HTTP/HTTPS proxy to connect to
var proxy = process.env.http_proxy || 'http://bc-proxy-vip.de.pri.o2.com:8080';
console.log('using proxy server %j', proxy);
// HTTPS endpoint for the proxy to connect to
var endpoint = process.argv[2] || 'https://api.spatialbuzz.com/api/coverage/2010-11-22/near/address/ehrwalder%20str%2064%2081377/customer/CSIEK3QbW2cycVMMWXddBR4xZl5yVA5QAVo/auth/84120D1A::F5305563';
console.log('attempting to GET %j', endpoint);
var options = url.parse(endpoint);
// Creating an instance of the `HttpsProxyAgent` class with the proxy server information
var agent = new HttpsProxyAgent(proxy);
options.agent = agent;
var req = await https.request(options, function(res) {
//console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
console.log(res.data); // *** null value undefined
res.pipe(process.stdout); // *** Working fine prints json resonse in server side
responsedata = res.data;
///responsedata1 = res.on('data', function (chunk) {
//console.log('BODY: ' + chunk);
//responsedata = ('BODY: ' + chunk);
//responsedata += chunk;
//console.log(responsedata);
//return (responsedata);
});
//console.log(responsedata); // *** Printing null value
// });
// req.on('error', (e) => {
// console.log(`problem with request: ${e.message}`);
//});
req.end();
response.send("Helloworld") // *** WORKING printing helloworld in client side
//response.send('responsedata'); // NOT WORKING printing null repsonse})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
解决方案
推荐阅读
- r - 从 R 的嵌套列表中的每个列表中采样 1 个元素以创建样本组
- pandas - Pandas Dataframe:前两列的Groupby并计算第一列的出现
- reactjs - ReactNative 错误,带有有效负载的操作'NAVIGATE'未被任何导航器处理
- r - if (a[i][j] > 4) { 中的错误:需要 TRUE/FALSE 的缺失值
- android - 使用改造在 android 中解析这个嵌套的 JSON 数组
- reactjs - 我应该遵循哪个指南来构建应用程序:Spring Boot (REST)+React+OKTA
- python - 如何查找距离 b/w 地理位置 w/ 测地线 w/ 坐标分为 4 个不同的列以创建距离列--ValueError
- power-automate - 如何使用 Power Automate 提取特定 URL?
- python - 在使用 python 正则表达式模块的行中查找锚标记的问题
- docker - 如何查看容器的日志?