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

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

问题描述

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

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

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

callback = function(response){

response.on('data',function(chunk){
str + = chunk;
} );
$ b response.on('end',function(){
console.log(str);
});

// return str;
}

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

//这些只是返回未定义的和空的
console.log(req.data);
console.log(str);


解决方案

当然, code> undefined :您在请求完成之前记录日志。问题不在于作用域,而是异步

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

  callback = function(response){

response.on('data',function(chunk){
str + = chunk;
}) ;
$ b response.on('end',function(){
console.log(req.data);
console.log(str);
//你的代码在这里,如果你想使用结果!
});
}

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


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

解决方案

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

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获取请求中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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