Node.js和未定义的属性

我试图使用GETvariables来传输一些简单的数据,但由于某种原因,我做错了。

我的代码很简单。 我使用Node.js HTTP和URL库。 当我尝试运行下面的代码时,我得到TypeError:无法读取未定义的属性'foo'。 我真的不明白为什么,因为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") 

你的问题不是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请求没有获得参数,你只需要检查q是不是undefined