1

I'm trying to use GET variables to transfer some simple data but for some reason I'm doing it wrong.

My code is pretty simple. I use Node.js HTTP & URL libraries. When I try to run following code, I get TypeError: Cannot read property 'foo' of undefined. 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.

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

1 Answer 1

4

Your problem is not that foo doesn't exist, the problem is that q itself is 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Aah, of course.. favicon request. Didn't thought of that. I really haven't done much server-side javascript with Node.js yet so all these little gotchas are biting me :/
I had something similar in a switch statement. The url.parse was outside the switch statement and some cases (like an xml format) did not return the params. As a result url.parse was undefined in those cases.
Is /favicon.ico always returned by default? Is there a way to avoid it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.