0

I have a url with a boolean query param: www.myUrl.com?foo=true

on my server, I have the following:

if (req.query.foo) {
   //do something
}

but then realized that was just checking for the presence of the param and not the value so that if I did www.myUrl.com?foo=asdasd, it'd still pass the conditional .

I then changed it to this (checking against a string) :

if (req.query.foo === 'true') {
   //do something
}

and that seems to work as intended. However, should I be using a boolean instead though, like req.param.foo === true (comparing against a boolean rather a 'true' string)?

  • Does this answer your question? https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Christian Apr 21 '21 at 07:08

1 Answers1

0

When express gets a request, it gets a string URL. It parses the query string from this URL and puts all values as string, because that's the way it got it. Express won't do any "estimations" about the type of each parameter because it really can't know what you as a developer expected to receive and also to "normalize" all parameters, so you will always know to expect for a string.

Therefore, if you want to compare against a boolean, you will need convert the string to boolean, but you really don't have to do so, and checking against the string should be good enough.

Matan Kadosh
  • 1,669
  • 3
  • 18
  • 24