【问题标题】:Passing data from Nodejs http get request从 Nodejs http get 请求传递数据
【发布时间】:2019-10-17 13:46:51
【问题描述】:

我正在尝试从 resp.on 函数的 get 请求中传递数据。我想使用 'var url' 发出一个单独的 get 请求,从中我将再次解析数据。我能够从函数内部 console.log 变量但不能返回(或从外部访问)。这似乎是一个范围界定或异步问题。

const https = require('https');

https.get('https://collectionapi.metmuseum.org/public/collection/v1/objects', (resp) => {
    let data = '';

    // A chunk of data has been recieved.
    resp.on('data', (chunk) => {
      data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
      var json_data = JSON.parse(data);
      var total = json_data.total
      var random_objectID = Math.floor(Math.random()*total)
      var url = 'https://collectionapi.metmuseum.org/public/collection/v1/objects/' + random_objectID
      console.log(url);
    });

  }).on("error", (err) => {
    console.log("Error: " + err.message);
  })

//'url' becomes unknown here. I want to pass it to another get request.

【问题讨论】:

  • 因为它超出范围尝试在之前声明它

标签: javascript node.js


【解决方案1】:

这既是异步问题,也是范围问题!

如果您在最外层范围内声明var url;,您将能够按预期在该回调中设置它,但由于这是异步发生的,您将无法在范围外使用该值,除非您在之后检查回调完成。

或者,您可以将整个内容包装在 promise 中,例如

const https = require('https');

new Promise((resolve,reject)=>{
  let targetUrl = 'https://collectionapi.metmuseum.org/public/collection/v1/objects';
  https.get(targetUrl,resp=>{
    // ...
    resp.on('end', () => {
      // ...
      resolve(url);
    });
  });
}).then(url=>{
// do stuff with that URL
});

如果您的目标是自动从网络资源中获取数据,我建议您查看request module,它也有一个承诺变体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-13
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多