1

我正在尝试验证查询字符串参数“hccid”,如下所示。似乎验证对我不起作用。有人可以看到我缺少什么吗?

const fastify = require('fastify')({
  ajv: {
        removeAdditional: true,
        useDefaults:      true,
        coerceTypes:      true
    }
});


const schema = {
    querystring: {
       hccid: { type: 'string' }
    }
};

// Declare a route
 fastify.get('/hello', {schema}, function (request, reply) {
    const hccid = request.query.hccid;
    reply.send({ hello: 'world' })
});

// Run the server!
fastify.listen(3000, function (err) {
if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
});

因此,使用该代码,当我使用全新的查询参数调用服务时,我应该得到一个模式验证异常,abc如下所示

http://localhost:3000/hello?abc=1

但没有错误。我得到了回复{"hello":"world"}

我还尝试一起删除查询参数http://localhost:3000/hello

我仍然得到{"hello":"world"}

所以显然验证不起作用。我的代码中缺少什么?任何帮助,将不胜感激。

4

2 回答 2

3

这个架构结构解决了我的问题。以防万一有人想检查一下是否遇到类似问题。

const querySchema = {
    schema: {
       querystring: {
         type: 'object',
           properties: {
             hccid: {
               type: 'string'
             }
         },
       required: ['hccid']
     }
  }
}
于 2017-12-24T14:01:18.090 回答
0

根据文档,您可以使用querystringorquery来验证查询字符串并params验证路由参数。

参数将是:

  • /api/garage/:id参数在哪里id可以访问request.params.id
  • /api/garage/:plate参数在哪里plate可以访问request.params.plate

参数验证的示例是:

const getItems = (req, reply) => {
  const { plate } = req.params;
  delete req.params.plate;
  reply.send(plate);
};

const getItemsOpts = {
  schema: {
    description: "Get information about a particular vehicle present in garage.",
    params: {
      type: "object",
      properties: {
        plate: {
          type: "string",
          pattern: "^[A-Za-z0-9]{7}$",
        },
      },
    },
    response: {
      200: {
        type: "array",
      },
    },
  },
  handler: getItems,
};

fastify.get("/garage/:plate", getItemsOpts);
done();

查询/查询字符串将是:

  • /api/garage/id?color=white&size=smallwherecolor和是在orsize处可访问的两个查询字符串。request.query.colorrequest.query.size

请参考上述答案作为查询验证的示例。

验证

路由验证内部依赖于Ajv v6,它是一个高性能 JSON Schema 验证器。验证输入非常简单:只需在路由模式中添加您需要的字段,就完成了!

支持的验证是:

  • body:验证请求的主体,如果它是 POST、PUT 或 PATCH 方法。
  • querystringquery:验证查询字符串。
  • params: 验证路由参数。
  • headers:验证请求标头。

[1] Fastify 验证:https ://www.fastify.io/docs/latest/Validation-and-Serialization/#validation

[2] Ajv@v6:https ://www.npmjs.com/package/ajv/v/6.12.6

[3] Fastify 请求:https ://www.fastify.io/docs/latest/Request/

于 2021-09-18T10:19:42.383 回答