node.js - nodejs TypeError: Cannot read property 'url' of undefined

查看:1173
本文介绍了node.js - nodejs TypeError: Cannot read property 'url' of undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

node菜鸟学院node.js路由的学习中提供了一个例子
代码如下:

var http=require('http');
var url=require('url');

function start(route) {
    function onRequest(request,response) {
        var pathname=url.parse(request.url).pathname;
        console.log('Request for'+pathname+'receiver');

        route(pathname);

        response.writeHead(200,{"Content-Type":"text/plain"});
        response.write('Hello Node');
        response.end();
    }
    http.createServer(onRequest()).listen(8888);
    console.log('Server has started');
}
exports.start=start;

当我启动服务的时候提示:

TypeError: Cannot read property 'url' of undefined
    at onRequest (C:\Users\zhengjh\Desktop\test\start.js:6:39)
    at Object.start (C:\Users\zhengjh\Desktop\test\start.js:15:23)
    at Object.<anonymous> (C:\Users\zhengjh\Desktop\test\index.js:3:7)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

http和url不是nodejs提供的原生模块吗?为什么会出现加载不了的问题,求解

解决方案

报错位置写得很清楚了,并不是模块不存在,而是第6行的request.url不存在。
原因下面写错了:

http.createServer(onRequest()).listen(8888);
=>
http.createServer(onRequest).listen(8888);
这里参数是个回调函数而不是一个已经被执行的回调函数。

这篇关于node.js - nodejs TypeError: Cannot read property &#039;url&#039; of undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆