我正在尝试使用 GET 变量来传输一些简单的数据,但由于某些原因我做错了。
我的代码非常简单。我使用 Node.js HTTP 和 URL 库。当我尝试运行以下代码时,出现类型错误:无法读取未定义的属性“foo”。我真的不明白为什么因为 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")
最佳答案
你的问题不是 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
。
关于javascript - Node.js 和未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277694/