2012-09-10 82 views
3

我创建了一个服务器的HTTP监听器:在NodeJs服务器中提出请求?

var http = require('http'); 
http.createServer(function (req, res) 
{ 
     res.writeHead(200, 
     { 
       'Content-Type': 'text/plain' 
     }); 
     res.write('aaa'); 
     res.end(); 
}).listen(1337, '127.0.0.1'); 
console.log('waiting......'); 

它正在查找并做响应。

enter image description here

现在,我想 - 的foreach客户端请求 - 要执行的服务器另一请求和追加字符串"XXX"

所以我写了:

var http = require('http'); 
var options = { 
     host: 'www.random.org', 
     path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new' 
}; 
http.createServer(function (req, res) 
{ 
     res.writeHead(200, 
     { 
       'Content-Type': 'text/plain' 
     }); 
     res.write('aaa'); 

     http.request(options, function (r) 
     { 
       r.on('data', function (chunk) 
       { 
         res.write('XXX'); 
       }); 
       r.on('end', function() 
       { 
         console.log(str); 
       }); 
       res.end(); 
     }); 

     res.end(); 
}).listen(1337, '127.0.0.1'); 
console.log('waiting......'); 

所以现在是foreach请求,应该写:aaaXXX(aaa + XXX)

但它不工作。它仍然产生了相同的输出。

我什么东错了?

+0

查找socket.io什么WebSocket'ish 。开箱即用的Node仍然只是一个基本的HTTP服务器。实时部分来自WebSockets。 – jolt

+2

@psycketom但是这个基本的Http服务器_can_可以提出他自己的另一个请求。那是我的问题。 :) –

回答

1

试试这个:

var http = require('http'); 
var options = { 
     host: 'www.random.org', 
     path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new' 
}; 
http.createServer(function (req, res) 
{ 
     res.writeHead(200, 
     { 
       'Content-Type': 'text/plain' 
     }); 
     res.write('aaa'); 

     var httpreq = http.request(options, function (r) 
     { 
      r.setEncoding('utf8'); 
      r.on('data', function (chunk) 
      { 
       res.write(' - '+chunk+' - '); 
      }); 
      r.on('end', function (str) 
      { 
       res.end(); 
      }); 

     }); 

     httpreq.end(); 

}).listen(1337, '127.0.0.1'); 
console.log('waiting......'); 

此外,值得一读节点this article on nodejitsu

+0

我曾告诉过你 - 我爱你吗? :-) 非常感谢。它正在工作 –

+0

问题是什么? –

+1

首先,我删除了'res.end()',因为之前的'http.request'是异步的,我们应该等待它完成,另一部分是我们需要'.end()''http .request'使其实际执行(我们可以在'.end()'之前发布一些数据,这就是为什么我们有这种方法) –

0

你打电话给res.end()太早了......你只想在事情写完之后做事情(例如,当调用r.on('end')时)。

对于这样的事情,我会高度推荐使用优秀的请求库(https://github.com/mikeal/request)。

这有一个美好的API,例如:

var request = require('request'); 
request('http://www.google.com', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body) // Print the google web page. 
    } 
}) 
+0

仍然,删除后,“结束”(第一个)不工作......为什么他不能再提出请求和concat字符串? (我没有改变你的解决方案,但我试图找出为什么myne不工作) –