Node.js的url.parse和查询字符串行为



给定URL:

  1. http://somedomain.com/?s=something

  2. http://somedomain.com/?s=

  3. http://somedomain.com/

通过代码:

var queryData = url.parse(request.url, true).query;
if (queryData["s"]) {
    console.log("s present in hash");
} else {
    console.log("s NOT present in hash");
}

我希望URL 1和2测试为真。它们在我以前使用过的其他语言库中也有。在查询字符串解析代码中,他们不将#2视为{"s":null},只是不将s放入哈希中
如果我想要这种行为,我是否应该使用另一个节点包,或者我应该能够在querystring中测试s var的另一种方式?

您的变量s在散列中。它等于一个空字符串,这正是你在URL中所拥有的。当被强制为布尔值时,它将计算为false

> url.parse('http://somedomain.com?s=', true).query
{ s: '' }
> !!url.parse('http://somedomain.com?s=', true).query.s
false

最新更新