[英]How to get number of request query parameters in express.js?
At the moment I have to check every potentially existing parameter separately. 目前,我必须分别检查每个可能存在的参数。
if (req.query.param1 != undefined ) {
}
if (req.query.param2 != undefined ) {
}
if (req.query.param3 != undefined ) {
}
...
To get all query parameter: 要获取所有查询参数:
Object.keys(req.query)
To get number of all params: 要获取所有参数的数量:
Object.keys(req.query).length
Then you can iterate through all parameters: 然后,您可以遍历所有参数:
for(p in req.query) {
//... do something
}
UPD: UPD:
surround your request with quotes to make right query 用引号括住您的请求以进行正确的查询
curl -X GET "localhost:9090/mypath?param1=123¶m2=321"
without quotes the &
in terminal makes the command run in the background. 不带引号的&
in终端使命令在后台运行。
If you hit /mypath?param1=5¶m2=10
, then the request.query
will yield {param1: 5, param2:10}
. 如果您命中/mypath?param1=5¶m2=10
,则request.query
将产生{param1: 5, param2:10}
。
This means that the request.query
is a JavaScript object with the key
as the name of the param, and value
as the value of the param. 这意味着, request.query
与JavaScript对象key
作为参数的时名称和value
作为参数的时值。 Now you can do anything with it as you want: Find the length or iterate over it as follows: 现在,您可以根据需要对其进行任何操作:找到长度或对其进行迭代,如下所示:
for (var key in request.query) {
if (request.query.hasOwnProperty(key)) {
alert(key + " -> " + request.query[key]);
}
}
Finding only the length
might not work for you that well because you may have param1
and param3
, with param2
missing. 仅查找length
可能不太适合您,因为您可能具有param1
和param3
,而param2
丢失了。 Iterating will be better IMO. 迭代将是更好的IMO。
You want the number of non-undefined params right? 您想要数量未定义的参数对吗? It is as simple as this; 就这么简单;
var no = 0;
for (var key in req.query) {
if(req.query[key]) no++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.