我正在閱讀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
。 我在做什麼錯?
非常感謝你,這是我自己可怕的錯誤。 – franza