简体   繁体   English

Node.js和未定义的属性

[英]Node.js and undefined properties

I'm trying to use GET variables to transfer some simple data but for some reason I'm doing it wrong. 我正在尝试使用GET变量来传输一些简单的数据,但由于某种原因,我做错了。

My code is pretty simple. 我的代码非常简单。 I use Node.js HTTP & URL libraries. 我使用Node.js HTTP和URL库。 When I try to run following code, I get TypeError: Cannot read property 'foo' of undefined. 当我尝试运行以下代码时,我得到TypeError:无法读取未定义的属性'foo'。 I really don't understand why because foo is passed in the URL and if I do console.log to q object, there's foo value. 我真的不明白为什么因为foo是在URL中传递的,如果我将console.log作为q对象,那就有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")

Your problem is not that foo doesn't exist, the problem is that q itself is undefined . 你的问题不是foo不存在,问题是q本身是undefined

Where does that come from? 它来自哪里? Well if we clean it up and add some logs... 好吧,如果我们清理它并添加一些日志......

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");

..we find out that the browser requests: ..我们发现浏览器要求:

/bla?foo=1
/favicon.ico

There you go! 你去! Of course the favicon request has not GET params, you simply need to check that q is not undefined . 当然,favicon请求没有GET参数,你只需要检查q是不是undefined

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

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