2012-09-07 84 views
3

我正在閱讀http://www.nodebeginner.org中的教程,在數據輸出中我有一個奇怪的行爲。我知道,在Stackoverflow上有類似的問題,但沒有答案。所以,我有web服務器的驗證碼node.js中的奇怪行爲

 
//server.js 
var http = require('http') 
var url = require('url') 

function start(route, handle) { 
    function onRequest(request, response) { 
     var postData = "" 
     var pathname = url.parse(request.url).pathname 
     console.log("Request for " + pathname + " recieved.") 

     request.setEncoding('utf8') 
     request.addListener("data", function(postDataChunk) { 
      postData += postDataChunk 
      console.log("Recieved POST data chunk '" + postDataChunk +"'.") 
     }) 

     request.addListener("end", function() { 
      route(handle, pathname, response, postData) 
     }) 
     var content = route(handle, pathname, response) 
    } 

    http.createServer(onRequest).listen(80, '192.168.1.34') 
    console.log("Server has started") 
} 

exports.start = start 

router.js準則這就要求requestHandler.upload - 我的車功能

 
//router.js 
function route(handle, pathname, response, postData) { 
    console.log("About to route a request for " + pathname) 
    if (typeof handle[pathname] === 'function') { 
     handle[pathname](response, postData) //calls requestHandler.upload 
    } else { 
     console.log("No request handler found for " + pathname) 
     response.writeHead(404, {'Content-Type' : 'text/plain'}) 
     response.write("404 Not found") 
     response.end() 
    } 
} 

而且requestHandler.upload

的代碼
 
//requestHandler.js 
function upload(response, postData) { 
    console.log("Request handler 'upload' was called with POST data: " + postData); //works fine 
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.write("You've sent: " + postData); //works ugly 
    response.end(); 
} 

我們假設在POST數據中有一個字符串text=123。該功能的第一行輸出真實數據,如"Request handler 'upload' was called with POST data: text=123"。雖然,這行response.write("You've sent: " + postData);在瀏覽器中輸出下一條消息:You've sent: undefined。 我在做什麼錯?

回答

2

在你的代碼中server.js行:

var content = route(handle, pathname, response) 

正在運行首先在"end"事件偵聽器的調用之前,執行的功能,但省略postData說法。它運行...

response.write("You've sent: " + postData); 
response.end(); 

因此,發送回瀏覽器的響應是:

You've sent: undefined 

被觸發後的"end"事件和事件偵聽器調用...

route(handle, pathname, response, postData) 

哪一個正確通過了postData,這會正確輸出到控制檯。 response.write(...)的呼叫不會第二次回發給瀏覽器,因爲此時的響應已結束。

我希望能解釋這個問題。

編輯答案是刪除通話

var content = route(handle, pathname, response) 

當客戶端已完成發佈的數據,你是正確運行在這一點上route功能"end"事件將被調用。

+0

非常感謝你,這是我自己可怕的錯誤。 – franza