如何从 Node.js http get 请求中获取数据 [英] How to get data out of a Node.js http get request

查看:91
本文介绍了如何从 Node.js http get 请求中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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);
}

推荐答案

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

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

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

http.request is 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):

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();

这篇关于如何从 Node.js http get 请求中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆