【问题标题】:Multiple types in query string in nodejsnodejs中查询字符串的多种类型
【发布时间】:2019-05-12 02:47:22
【问题描述】:

我正在 nodejs 中创建一个 get api。我正在请求以下 url

http://localhost:8080/api?id=20&condition1=true&arr=[{prop1:1}]&obj={a:1,b:2} 我得到的请求查询对象如下-

req.query = {
   arr:"[{prop1:1}]",
   condition1:"true",
   id:"20",
  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 对象是动态的,它可以包含任意数量的对象、数组、布尔值、数字或字符串。有什么办法吗?

【问题讨论】:

  • 您的键值将用逗号分隔,对吗?喜欢req.query = { arr:"[{prop1:1}]", condition1:"true", id:"20", obj:"{a:1,b:2}" , }
  • 是的@ShamsNahid。感谢您建议编辑。你能帮我解决这个问题吗
  • 让我试试。当然,有人会帮助你。
  • 为什么不简单地使用 post 请求?
  • @Praveen 因为这应该是一个get请求,所以我使用查询对象来过滤掉结果。

标签: node.js express parsing request.querystring


【解决方案1】:

express 和查询参数并非开箱即用此功能。

问题在于,为了让查询字符串解析器知道"true" 是实际布尔值true 还是字符串"true",它需要某种Schema 来帮助查询对象解析字符串。

选项 A

我可以推荐的是使用Joi

在你的情况下,它看起来像:

const Joi = require( "joi" );


const querySchema = {
    arr: Joi.array(),
    condition1: Joi.boolean(),
    id: Joi.number(),
    obj: {
      a: Joi.number(),
      b: Joi.number()
    }
}

拥有此架构,您可以将其附加到您的 express 方法并使用 Joi.validate 来验证它。

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
}

【讨论】:

  • 查询字符串将是动态的,即我不知道哪个查询参数将是数组、对象或布尔值。你能为这个问题推荐一些软件包吗?而且我不能使用选项 B,因为 JSON.parse 在字符串的情况下会出错
  • 您可以使用try { const data = JSON.parse( req.query.data ) } catch ( error ) { // Not JSON }。这将捕获 JSON.parse 的错误
猜你喜欢
  • 2023-03-04
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 2022-01-07
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多