最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js Express req.query is undefined - Stack Overflow

programmeradmin0浏览0评论

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 e the query param is not passed in?

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 e the query param is not passed in?

Share Improve this question asked Sep 2, 2014 at 3:48 Ron HarlevRon Harlev 16.7k26 gold badges92 silver badges138 bronze badges 4
  • How are you "calling the URL"? Using cURL? A browser? Something else? – mscdex Commented Sep 2, 2014 at 3:55
  • Both a browser (chrome) and Postman. Same result – Ron Harlev Commented Sep 2, 2014 at 3:56
  • I had this problem. Turns out it was a spelling mistake. I was using querry instead of query – DollarAkshay Commented May 9, 2018 at 11:23
  • Can you console log req.query object and see what is the result – Sandeep Patel Commented Jul 11, 2018 at 8:49
Add a ment  | 

2 Answers 2

Reset to default 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}.

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;
发布评论

评论列表(0)

  1. 暂无评论