【问题标题】:Node.js and undefined propertiesNode.js 和未定义的属性
【发布时间】:2010-11-25 21:52:31
【问题描述】:

我正在尝试使用 GET 变量来传输一些简单的数据,但由于某种原因我做错了。

我的代码很简单。我使用 Node.js HTTP 和 URL 库。当我尝试运行以下代码时,我得到 TypeError: Cannot read property 'foo' of undefined。我真的不明白为什么,因为 foo 是在 URL 中传递的,如果我对 q 对象执行 console.log,就会有 foo 值。

http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'})
   var vars = url.parse(req.url,true)
   var q = vars.query
   if(q.foo) {
      res.end('yay')
   } else res.end('snif')
 }).listen(8000,"127.0.0.1")

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    你的问题不是foo不存在,问题是q本身就是undefined

    这是从哪里来的?好吧,如果我们清理它并添加一些日志...

    var http = require('http');
    var url = require('url');
    
    http.createServer(function (req, res) {
        console.log(req.url);
    
        res.writeHead(200, {'Content-Type': 'text/plain'});
        var vars = url.parse(req.url, true);
        var q = vars.query;
        if(q && q.foo) { // this time check that q has a value (or better check that q is an object)
            res.end('yay');
    
        } else {
            res.end('snif');
        }
    }).listen(8000,"127.0.0.1");
    

    ..我们发现浏览器请求:

    /bla?foo=1
    /favicon.ico
    

    给你!当然favicon请求没有GET参数,你只需要检查q不是undefined

    【讨论】:

    • 啊,当然.. 网站图标请求。没想到。我真的没有用 Node.js 做太多的服务器端 javascript,所以所有这些小问题都在咬我:/
    • 我在 switch 语句中有类似的东西。 url.parse 在 switch 语句之外,某些情况(如 xml 格式)没有返回参数。因此,url.parse 在这些情况下是未定义的。
    • /favicon.ico是否总是默认返回?有办法避免吗?
    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 2019-10-20
    • 1970-01-01
    • 2016-05-09
    • 2021-12-05
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多