简体   繁体   English

从 Nodejs 传递数据 http 获取请求

[英]Passing data from Nodejs http get request

I am trying to pass data out of my get request from resp.on function.我正在尝试将数据从来自 resp.on function 的 get 请求中传递出去。 I want to use 'var url' to make a separate get request from which I will parse data again.我想使用 'var url' 发出一个单独的获取请求,我将再次解析数据。 I am able to console.log variables from inside the function but not return (or access from outside).我能够从 function 内部 console.log 变量,但不能返回(或从外部访问)。 This seems to be a scoping or async issue.这似乎是一个范围界定或异步问题。

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.

It's both an async and a scope issue!它既是异步问题又是 scope 问题!

If you declare var url;如果您声明var url; in the outermost scope you'll be able to set it inside that callback as intended, but since that's happening asynchronously you won't be able to use the value outside the scope unless you are checking after the callback completes.在最外面的 scope 中,您将能够按预期在该回调中设置它,但由于这是异步发生的,您将无法使用 scope 之外的值,除非您在回调完成后进行检查。

Alternatively, you could wrap the whole thing in a promise , eg或者,您可以将整个东西包装在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
});

If your goal is to automate fetching data from web resources, I'd recommend checking out the request module , which also has a promisified variant.如果您的目标是自动从 web 资源中获取数据,我建议您查看request 模块,它也有一个承诺的变体。

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

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