Node.js中查询字符串中的多种类型 [英] Multiple types in query string in nodejs
问题描述
我正在nodejs中创建一个get api.我正在请求以下URL
I am creating a get api in nodejs.I am requesting the following url
> http://localhost:8080/api?id = 20&; condition1 = true& arr = [ {prop1:1}]& obj = {a:1,b:2}我得到的请求查询对象如下-
http://localhost:8080/api?id=20&condition1=true&arr=[{prop1:1}]&obj={a:1,b:2} And I am getting the request query object as follows-
req.query = {
arr:"[{prop1:1}]",
condition1:"true",
id:"20",
obj:"{a:1,b:2}"
}
我想将查询对象键转换为适当的类型.我的查询对象应转换为
I want to convert the query object keys to appropriate types.My query object should be converted to
req.query = {
arr:[{prop1:1}], // Array
condition1:true, // Boolean
id:20, // Number
obj: {a:1,b:2} //Object
}
req.query对象是动态的,它可以包含任意数量的对象,数组,布尔值,数字或字符串.有什么办法吗?
req.query object is dynamic, it can contain any number of objects, array, boolean , number or strings. Is there any way to do it?
推荐答案
使用 express
和查询参数无法立即使用此功能.
This functionality doesn't come out of the box with express
and query parameters.
问题是,为了让查询字符串解析器知道"true"
是实际的布尔值 true
还是字符串"true"
查询对象需要某种 Schema
来帮助解析字符串.
The problem is that in order for the query string parser to know if "true"
is actual boolean true
or the string "true"
it needs some sort of Schema
for the query object to help parsing the string.
选项A
我推荐使用 Joi .
在您的情况下,它看起来像是:
In your case it will look like :
const Joi = require( "joi" );
const querySchema = {
arr: Joi.array(),
condition1: Joi.boolean(),
id: Joi.number(),
obj: {
a: Joi.number(),
b: Joi.number()
}
}
具有此架构,您可以将其附加到您的express方法上,并使用
Having this schema you can attach it to your express method and use Joi.validate
To validate it.
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.
Another way of having properly typed GET requests would be to trick the query parameters and just provide a stringified JSON.
GET localhost/foo?data='{"foo":true,"bar":1}'
这将使您可以解析请求查询
This will give you the possibility to just parse the request query
function getFoo( req, res, next ) {
const data = JSON.parse( req.query.data )
data.foo // boolean
data.bar // number
}
这篇关于Node.js中查询字符串中的多种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!