簡體   English   中英

Node.js和未定義的屬性

[英]Node.js and undefined properties

我正在嘗試使用GET變量來傳輸一些簡單的數據,但由於某種原因,我做錯了。

我的代碼非常簡單。 我使用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請求沒有GET參數,你只需要檢查q是不是undefined

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM