繁体   English   中英

从 Nodejs 传递数据 http 获取请求

[英]Passing data from Nodejs http get request

我正在尝试将数据从来自 resp.on function 的 get 请求中传递出去。 我想使用 'var url' 发出一个单独的获取请求,我将再次解析数据。 我能够从 function 内部 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.

它既是异步问题又是 scope 问题!

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

或者,您可以将整个东西包装在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
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM