2013-03-04 45 views
2

我不知道爲什麼這樣simple http request是不工作...的Node.js簡單的HTTP請求不起作用

http = require("http") 

url = "http://nodejs.org/" 

console.log "Try a request to #{url}..." 
reqHttp = http.request url, (response) -> 

    console.log "Request to #{url}" 
    response.on 'data', (chunk) -> console.log "chunk: ", chunk 

reqHttp.on 'error', (error) -> console.log "reqHttp error", error 

一分鐘左右後返回:

reqHttp error { [Error: socket hang up] code: 'ECONNRESET' } 

,以確保它是不是我的環境出了問題,我嘗試了request模塊和工作得很好:

request = require("request") 

url = "http://nodejs.org/" 

request url, (error, response, body) -> 
    console.log body if not error and response.statusCode is 200 

似乎I'm not the only one

所以,我有一個解決方案,我的問題(使用request模塊),但我想知道爲什麼我不能使用buind在HTTP請求。它是越野車還是不可靠? (Node.js版本0.8.21)

+0

你能格式化你的代碼嗎,很難說沒有任何括號 – user568109 2013-03-04 15:09:36

+0

對不起。我忘了提及它是咖啡標記。您可以使用http://coffeescript.org/#try:查看js抄錄。但基本上,功能範圍是由相關空間決定的。 – 2013-03-04 15:11:49

回答

7

好的,這很簡單。您正在構建一個http request,但未完成發送。從鏈接你給自己:

req.write('data\n'); //Write some data into request 
req.write('data\n'); 
req.end();    //Finish sending request let request go. Please do this 

既然你從未使用過req.end(),它就掛了,因爲它從來沒有得到完成。節點重置非活動請求

reqHttp error { [Error: socket hang up] code: 'ECONNRESET' } 
+0

謝謝!只需將'req.end()'放在代碼的末尾,它就可以工作。 我認爲可以質疑API設計和所有...無論哪種方式,它的工作。謝謝! – 2013-03-04 16:33:21