4

I'm running the following code on Node.js with Express 4.7.2

express.get('/test1',function(req, res) {
  var ttt = false;
  if (req.query.username === undefined) ttt = true;
  res.json({query: ttt});
});

I call the URL:

{{protocol}}://{{server}}/test1?username=1

And I get the result:

{query: true}

Which shows req.query.username is indeed undefined

What am I missing? How come the query param is not passed in?

Ron Harlev
  • 16,227
  • 24
  • 89
  • 132

2 Answers2

3

The code you've shown works fine for me with node v0.10.30 and express 4.8.7:

var app = require('express')();

app.get('/test1',function(req, res) {
  var ttt = false;
  if (req.query.username === undefined) ttt = true;
  res.json({query: ttt});
});

app.listen(8000);

I then navigate to http://localhost:8000/test1?username=1 and it displays {"query":false}.

mscdex
  • 104,356
  • 15
  • 192
  • 153
0

It seams that query typeof is string, and string of "undefined" is truthy.

In your code it should be:

if (req.query.username === "undefined")
  ttt = true;
Tyler2P
  • 2,324
  • 26
  • 22
  • 31