Node.js nodejs中查询字符串中的多个类型
我正在nodejs中创建一个getapi {prop1:1}]&obj={a:1,b:2} 我得到的请求查询对象如下- 我想将查询对象键转换为适当的类型。我的查询对象应转换为Node.js nodejs中查询字符串中的多个类型,node.js,express,parsing,request.querystring,Node.js,Express,Parsing,Request.querystring,我正在nodejs中创建一个getapi {prop1:1}]&obj={a:1,b:2} 我得到的请求查询对象如下- 我想将查询对象键转换为适当的类型。我的查询对象应转换为 req.query = { arr:[{prop1:1}], // Array condition1:true, // Boolean id:20, // Number obj: {a:1,b:2} //Object } 查询对象是动态的,它可以包含任意数量的
req.query = {
arr:[{prop1:1}], // Array
condition1:true, // Boolean
id:20, // Number
obj: {a:1,b:2} //Object
}
查询对象是动态的,它可以包含任意数量的对象、数组、布尔值、数字或字符串。有什么办法吗?此功能不是与
express
和查询参数一起提供的
问题在于,为了让查询字符串解析器知道“true”
是实际的布尔值true
还是字符串“true”
,查询对象需要某种模式来帮助解析字符串
选项A
我可以推荐的是使用
在您的情况下,它将如下所示:
const Joi = require( "joi" );
const querySchema = {
arr: Joi.array(),
condition1: Joi.boolean(),
id: Joi.number(),
obj: {
a: Joi.number(),
b: Joi.number()
}
}
有了这个模式,您可以将它附加到express方法并使用它进行验证
function getFoo( req, res, next ) {
const query = req.query; // query is { condition1: "true" // string, ... }
Joi.validate( query, querySchema, ( err, values ) => {
values.condition1 === true // converted to boolean
} );
}
选项B
另一种正确键入GET请求的方法是欺骗查询参数,只提供字符串化的JSON
GET localhost/foo?data='{"foo":true,"bar":1}'
这将使您有可能只解析请求查询
function getFoo( req, res, next ) {
const data = JSON.parse( req.query.data )
data.foo // boolean
data.bar // number
}
您的键值将以逗号分隔,对吗?比如req.query={arr:[{prop1:1}]”,条件1:“true”,id:“20”,obj:{a:1,b:2},}
Yes@ShamsNahid。谢谢你的建议。你能帮我解决这个问题吗?让我试试。当然,有人会帮你。为什么不简单地使用post请求?@Praveen因为这应该是一个get请求,所以我使用查询对象来过滤结果。查询字符串将是动态的,即我不知道哪个查询参数将是数组、对象或布尔值。你能建议一些解决这个问题的方案吗。我不能使用选项B,因为JSON.parse会在string的情况下给出错误。您可以使用尝试{const data=JSON.parse(req.query.data)}catch(error){//Not JSON}
。这将捕获JSON.parse的错误
function getFoo( req, res, next ) {
const data = JSON.parse( req.query.data )
data.foo // boolean
data.bar // number
}