http.createServer的Node.jscallbacktypes错误

我对node.js非常陌生,正在玩弄几个教程,偶然发现这个问题做了一些重构。

我正在跟随的教程链接在这里: http : //www.tutorialspoint.com/nodejs/nodejs_web_module.htm

我决定拆分callback以使代码更具可读性,所以创build了一个文件读取器方法和一个“监视器”方法:

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 

显然这是一个types问题。 我正在寻找铸造http.incomingMessage,但我不熟悉的JavaScript和我的networkingsearch没有产生一个快速的解决scheme。

谢谢!

你的问题在这一行:

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

它应该是:

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

原因是因为你想通过监听function作为callback,而不是调用它。 在monitor之后放置括号将会调用没有参数的函数。 当参数没有被赋予该函数时,它们将取值为undefined ,因此会出现错误。