如何从 Node.js http get 请求中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19539391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:03:42  来源:igfitidea点击:

How to get data out of a Node.js http get request

javascriptnode.jshttpgetrequest

提问by Daryl Rodrigo

I'm trying to get my function to return the http get request, however, whatever I do it seems to get lost in the ?scope?. I'm quit new to Node.js so any help would be appreciated

我试图让我的函数返回 http get 请求,但是,无论我做什么,它似乎都迷失在 ?scope? 中。我是 Node.js 的新手,所以任何帮助将不胜感激

function getData(){
  var http = require('http');
  var str = '';

  var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
  };

  callback = function(response) {

        response.on('data', function (chunk) {
              str += chunk;
        });

        response.on('end', function () {
              console.log(str);
        });

        //return str;
  }

  var req = http.request(options, callback).end();

  // These just return undefined and empty
  console.log(req.data);
  console.log(str);
}

回答by Denys Séguret

Of course your logs return undefined: you log before the request is done. The problem isn't scope but asynchronicity.

当然您的日志返回undefined:您在请求完成之前登录。问题不在于范围,而在于异步性

http.requestis asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end):

http.request是异步的,这就是为什么它将回调作为参数。在回调中做你必须做的事情(你传递给的那个response.end):

callback = function(response) {

  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(req.data);
    console.log(str);
    // your code here if you want to use the results !
  });
}

var req = http.request(options, callback).end();

回答by Oded Breiner

Shorter example using http.get:

使用 http.get 的简短示例:

require('http').get('http://httpbin.org/ip', (res) => {
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log(body);
    });
});

回答by ezchx

from learnyounode:

来自learnyounode:

var http = require('http')  

http.get(options, function (response) {  
  response.setEncoding('utf8')  
  response.on('data', console.log)  
  response.on('error', console.error)  
})

'options' is the host/path variable

'options' 是主机/路径变量

回答by Elise Chant

from learnyounode:

来自learnyounode:

var http = require('http')
var bl = require('bl')

http.get(process.argv[2], function (response) {
    response.pipe(bl(function (err, data) {
        if (err)
            return console.error(err)
        data = data.toString()
        console.log(data)
    }))
})

回答by ackuser

This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback

这是我的解决方案,尽管您可以肯定地使用许多模块来为您提供对象作为承诺或类似的东西。无论如何,你错过了另一个回调

function getData(callbackData){
  var http = require('http');
  var str = '';

  var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
  };

  callback = function(response) {

        response.on('data', function (chunk) {
              str += chunk;
        });

        response.on('end', function () {
              console.log(str);
          callbackData(str);
        });

        //return str;
  }

  var req = http.request(options, callback).end();

  // These just return undefined and empty
  console.log(req.data);
  console.log(str);
}

somewhere else

别的地方

getData(function(data){
// YOUR CODE HERE!!!
})

回答by smsivaprakaash

Simple Working Example of Http request using node.

使用节点的 Http 请求的简单工作示例。

const http = require('https')

httprequest().then((data) => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
    return response;
});
function httprequest() {
     return new Promise((resolve, reject) => {
        const options = {
            host: 'jsonplaceholder.typicode.com',
            path: '/todos',
            port: 443,
            method: 'GET'
        };
        const req = http.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
       req.end();
    });
}

回答by Vaibhav Rai

I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array.

我认为现在回答这个问题为时已晚,但我最近遇到了同样的问题,我的用例是调用分页的 JSON API 并从每个分页中获取所有数据并将其附加到单个数组中。

const https = require('https');
const apiUrl = "https://example.com/api/movies/search/?Title=";
let finaldata = [];
let someCallBack = function(data){
  finaldata.push(...data);
  console.log(finaldata);
};
const getData = function (substr, pageNo=1, someCallBack) {

  let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
  let mydata = []
  https.get(actualUrl, (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
        data += chunk;
    });
    resp.on('end', async () => {
        if (JSON.parse(data).total_pages!==null){
          pageNo+=1;
          somCallBack(JSON.parse(data).data);
          await getData(substr, pageNo, someCallBack);
        }
    });
  }).on("error", (err) => {
      console.log("Error: " + err.message);
  });
}

getData("spiderman", pageNo=1, someCallBack);

Like @ackuser mentioned we can use other module but In my use case I had to use the node https. Hoping this will help others.

就像@ackuser 提到的,我们可以使用其他模块,但在我的用例中,我必须使用 node https。希望这会帮助其他人。