简体   繁体   English

http.createServer的Node.js回调类型错误

[英]Node.js callback type error with http.createServer

I am very new to node.js, and was playing around with a few tutorials and stumbled across this problem doing a little refactoring. 我对node.js还是很陌生,并且正在玩一些教程,偶然发现了这个问题,做了一些重构。

The tutorial I was following is linked here: http://www.tutorialspoint.com/nodejs/nodejs_web_module.htm 我正在关注的教程在这里链接: http : //www.tutorialspoint.com/nodejs/nodejs_web_module.htm

I decided to split out the callbacks to make the code a little more readable, so created a file reader method and a 'monitor' method: 我决定拆分回调以使代码更具可读性,因此创建了一个文件读取器方法和一个“监控”方法:

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

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

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

When I run this I get the following error: 运行此命令时,出现以下错误:

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

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

Clearly this is a type issue. 显然,这是一个类型问题。 I was looking into casting to http.incomingMessage, but am not familiar enough with javascript and my web searching did not yield a quick solution. 我一直在尝试转换为http.incomingMessage,但对javascript不够熟悉,并且我的网络搜索没有提供快速的解决方案。

Thanks! 谢谢!

Your problem is in this line: 您的问题在这一行:

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

It should be: 它应该是:

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

The reason is because you want to pass the monitor function as a callback, not call it. 原因是因为您要将监视器函数作为回调传递,而不是调用它。 Placing the parenthesis after monitor will call the function with no arguments. monitor之后放置括号将调用不带参数的函数。 When arguments are not given to the function, they take on the value undefined , hence the error you're getting. 如果未将参数提供给函数,则它们的值将为undefined ,因此会出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM