Reputation: 25269
In node 6.x the querystring
module parses values into an object that does not extend from Object.prototype
(Although I have no idea why this change was made).
Given that, what is the expected way to check for query parameters that do not contain a value, i.e. someone called express or koa with localhost:8080/some/path?keyonly
and I want to check for the presence of this.query.keyonly
? I expected that I could do this.query.hasOwnProperty('keyonly')
which obviously doesn't work. What's the alternative?
Upvotes: 0
Views: 162
Reputation: 106706
For the background behind the change, see the original PR here.
In general, you should not rely on foo.hasOwnProperty()
since hasOwnProperty
could be easily reassigned to something else (hence the reason for the querystring
change -- imagine someone calling your web service with something like http://example.org/foo?hasOwnProperty=hahacrashed).
As far alternatives, you could just check if the property is defined, for example:
var qs = querystring.parse('foo=bar');
if (qs.foo !== undefined) {
// ...
}
You could also do something like:
var qs = querystring.parse('foo=bar');
if (Object.hasOwnProperty.call(qs, 'foo')) {
// ...
}
but that isn't as efficient because hasOwnProperty()
performs additional (and unnecesary in the case of querystring
now) checks and uses .call()
which is less efficient
Upvotes: 1
Reputation: 8344
Looks like you can use Object.hasOwnProperty.call( this.query, "keyonly" )
. I set up a bit of a contrived test case and it appears to work:
const querystring = require("querystring");
const qs = "keyonly&keyvalue=valuekey";
const result = querystring.decode(url);
console.log(Object.hasOwnProperty.call( result, "keyonly" )); // true
The &keyvalue=valuekey
part isn't necessary for it to work, I just wanted to verify that it wouldn't interfere somehow.
Upvotes: 1