express使用qs模块来解析查询字符串,但似乎所有内容都以字符串形式发送。
如何获取数字和布尔值?
app?flag=true&count=20
// => in express gives:
req.query.count === "20"
req.query.flag === "true"
// => whereas I want
req.query.count === 20 // number (int)
req.query.flag === true // boolean
这些查询参数中的都被解析为字符串,不得不做我自己的所有类型检查,parseInt等并进行转换真的很烦人。 也许有一个lib可以处理生成的对象?
其他qs库似乎也避开了这种简单的情况,尽管它们非常擅长于URL上编码的深层嵌套对象...
https://www.npmjs.com/package/query-string
queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'});
//=> {foo: ['1', '2', '3']}
Multiple types in query string in nodejs req.params.number is string in expressjs? https://github.com/cdeutsch/query-string-for-all https://www.npmjs.com/package/url-parse
答案 0 :(得分:0)
似乎您必须为解析函数编写自己的解码器选项,内容如下:
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;
}
}
})
信用来源:https://github.com/ljharb/qs/issues/91#issuecomment-437926409