如何从Node JS中的回调函数中获取数据?

时间:2013-10-23 12:31:44

标签: javascript node.js

我在从节点js的http.request获取数据时遇到问题我在控制台中获取了数据但是当我试图将其从函数中取出时它不会进入变量这里是我尝试发送请求时的代码端口转发我在x回调函数中得到了响应,但没有找到数据,所以任何知道的人都请告诉我。

var fs = require('fs');
var http = require('http');
var url = require('url') ,
httpProxy = require('http-proxy');
var express = require("express");


 //
 // Create your proxy server
//
httpProxy.createServer(9000, 'localhost').listen(8000);

 //
// Create your target server
//
 http.createServer(function (req, res) {

res.writeHead(200, { 'Content-Type': 'text/plain' });

//res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true,      2));

 var queryObject = url.parse(req.url,true).query;


 res.writeHead(200);
 if(queryObject['id']!==undefined){
  console.log(queryObject);
  //alert(queryObject['id']);
 if(queryObject['id'].match('100'))
{
  res.write(queryObject['id']+" forwarding to another port 8000");

  //sending request
  var options = {
            host: '192.168.10.33',
            port: 8080,
            path: '/demo.js?id='+queryObject['id'],
            method: 'GET',
            headers: {
                accept: 'text/plain'
            }
        };

        console.log("Start conecting ...");
        var x = http.request(options,function(res2){
            console.log("Connected.");
            res2.on('data',function(data){
  //*********
 //Here is the problem occur this data i m cloud not able to print 
 //********
                console.log("data-> "+data);

            });
        });

        x.end("\n ok");
  //end 

    }
   else
   {
  res.write("listening on current port");
  }
  }
   res.end("\n end of page ");//'\n\nFeel free to add query parameters to the end of the url');
 //res.end();
  }).listen(9000);

1 个答案:

答案 0 :(得分:2)

我认为响应数据是分块的,所以你需要继续加载数据并将其挂起到缓冲区,然后将其记录到控制台,数据完成后进行数据处理。

e.g。

var http = require('http');

//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
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) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

Src:http://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request