2015-12-12 29 views
1

我對node.js很新,並且正在玩弄幾個教程,偶然發現這個問題做了一點重構。Node.js回調類型錯誤與http.createServer

我下面的教程鏈接在這裏: http://www.tutorialspoint.com/nodejs/nodejs_web_module.htm

我決定分家出來的回調,使代碼更易讀,所以創建了一個文件閱讀方法和「監視」的方法:

function monitor(request, response) 
{ 
     var pathname = url.parse(request.url).pathname; 

     fs.readFile(pathname.substr(1), reader()); 
} 

http.createServer(monitor()).listen(8080); 

當我運行此我得到以下錯誤:

var pathname = url.parse(request.url).pathname; 
            ^

TypeError: Cannot read property 'url' of undefined 
    at monitor 

顯然,這是一個類型的問題。我正在尋找轉換爲http.incomingMessage,但我不熟悉javascript,我的網絡搜索沒有產生一個快速的解決方案。

謝謝!

回答

5

您的問題是在這條線:

http.createServer(monitor()).listen(8080); 

它應該是:

http.createServer(monitor).listen(8080); 

的原因是因爲你想通過監視功能的回調,而不是調用它。在monitor後放置圓括號將會調用沒有參數的函數。當參數沒有被賦予該函數時,它們的值爲undefined,因此出現錯誤。

+0

就是這樣,謝謝! – Dan

+0

非常歡迎!很高興我能夠提供幫助。 –