我正在尝试验证querystring参数'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}`)
});因此,使用该代码,当我用一个完全新的queryparam abc调用服务时,我应该得到一个模式验证异常,如下所示
http://localhost:3000/hello?abc=1但没有任何错误。我得到回复了,{"hello":"world"}
我还尝试将queryparam全部删除( http://localhost:3000/hello )
我还有{"hello":"world"}
所以很明显,验证是不起作用的。我的代码中遗漏了什么?任何帮助都将不胜感激。
发布于 2017-12-24 14:01:18
这个架构结构解决了我的问题。以防万一,如果有人想看看,如果他们遇到类似的问题。
const querySchema = {
schema: {
querystring: {
type: 'object',
properties: {
hccid: {
type: 'string'
}
},
required: ['hccid']
}
}
}发布于 2021-09-18 10:19:42
根据文档,可以使用querystring或query验证查询字符串,使用params验证路由参数。
伙伴关系将是:
/api/garage/:id,其中id是param可访问的request.params.id/api/garage/:plate,其中plate是request.params.plate上可访问的paramparam验证的示例如下:
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();Query / Querystring将是:
/api/garage/id?color=white&size=small,其中color和size是在request.query.color或request.query.size上可访问的两个查询字符串。请参考上述答案作为查询验证的示例。
验证 路由验证在内部依赖于Ajv v6,它是一个高性能的JSON验证器。验证输入非常简单:只需在路由模式中添加所需的字段,您就完成了! 所支持的验证是:
body:验证请求的主体,如果它是POST、PUT或修补方法。querystring或query:验证查询字符串。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/
https://stackoverflow.com/questions/47954210
复制相似问题