[英]Proper way to parse Boolean query string param in node/express
I'm waiting for something like the following from the front end我正在等待来自前端的类似以下内容
....?isUpdated=true
so I did something like this in code (as I'm processing only isUpdated=true
, false need to be ignored)所以我在代码中做了这样的事情(因为我只处理
isUpdated=true
, false 需要被忽略)
var isUpdated = (req.query.isUpdated === 'true')
but it seems bit odd to me.但对我来说似乎有点奇怪。
How to do this in proper way?如何以正确的方式做到这一点? I mean to parse a Boolean parameter from the query string.
我的意思是从查询字符串中解析一个布尔参数。
我使用这对线:
let test = (value).toString().trim().toLowerCase(); let result = !((test === 'false') || (test === '0') || (test === ''));
Here is my generic solution for getting a query params as a boolean:这是我将查询参数作为布尔值获取的通用解决方案:
const isTrue = Boolean((req.query.myParam || "").replace(/\s*(false|null|undefined|0)\s*/i, ""))
It converts the query param into a string which is then cleaned by suppressing any falsy string.它将查询参数转换为一个字符串,然后通过抑制任何虚假字符串来清除该字符串。 Any resulting non-empty string will be
true
.任何生成的非空字符串都将为
true
。
You can use qs package您可以使用qs包
A little code to parse int and booleans解析整数和布尔值的小代码
qs.parse(request.querystring, {
decoder(str, decoder, charset) {
const strWithoutPlus = str.replace(/\+/g, ' ');
if (charset === 'iso-8859-1') {
// unescape never throws, no try...catch needed:
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}
if (/^(\d+|\d*\.\d+)$/.test(str)) {
return parseFloat(str)
}
const keywords = {
true: true,
false: false,
null: null,
undefined,
}
if (str in keywords) {
return keywords[str]
}
// utf-8
try {
return decodeURIComponent(strWithoutPlus);
} catch (e) {
return strWithoutPlus;
}
}
})
The only thing I would change about your approach is to make it case insensitive:关于你的方法,我唯一要改变的是让它不区分大小写:
var isUpdated = ((req.query.isUpdated+'').toLowerCase() === 'true')
You could make this a utility function as well if you like:如果您愿意,也可以将其设为实用函数:
function queryParamToBool(value) {
return ((value+'').toLowerCase() === 'true')
}
var isUpdated = queryParamToBool(req.query.isUpdated)
var myBoolean = (req.query.myParam === undefined || req.query.myParam.toLowerCase() === 'false' ? false : true)
With some ideas from previous answers, I ended up using this function to consider undefined values as well有了之前答案的一些想法,我最终也使用此函数来考虑未定义的值
const parseBool = (params) => {
return !(
params === "false" ||
params === "0" ||
params === "" ||
params === undefined
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.