2012-09-10 81 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不工作) –