【发布时间】:2021-04-19 21:34:59
【问题描述】:
在路由上使用 fastify 和 schema 对象,我正在尝试添加更多验证。 fastify 使用(用于身体验证)ajv。按照 fastify 文档和代码,添加一个 ajv 插件我需要这样做:
const fastify = require('fastify')({
ajv: {
plugins: [
require('ajv-merge-patch')
]
}
})
文档是here
问题是当我们尝试添加这个插件时,我收到这个错误:Cannot read property 'code' of undefined" 这是堆栈错误:
TypeError: Cannot read property 'code' of undefined
at addFormats (/test-api/node_modules/ajv-formats/dist/index.js:30:26)
at Array.formatsPlugin (/test-api/node_modules/ajv-formats/dist/index.js:15:5)
at ValidatorCompiler (/test-api/node_modules/fastify/lib/schema-compilers.js:42:16)
at buildCompilerFromPool (/test-api/node_modules/fastify/lib/schema-compilers.js:20:22)
at Boot.<anonymous> (/test-api/node_modules/fastify/lib/route.js:269:39)
at Object.onceWrapper (events.js:421:28)
at Boot.emit (events.js:327:22)
at /test-api/node_modules/avvio/boot.js:153:12
at /test-api/node_modules/avvio/plugin.js:269:7
at done (/test-api/node_modules/avvio/plugin.js:201:5)"
这段代码出现了这个错误:
const server: FastifyInstance<Server, IncomingMessage, ServerResponse > = fastify({
ignoreTrailingSlash: true,
logger: true,
ajv: {
plugins: [
require('ajv-formats')
]
}
})
async function run (): Promise<string> {
server.addHook('onRoute', (options) => console.log(options))
await server.register(helmet)
await server.register(cors)
return server.listen(3000, 'localhost')
}
有人可以在 fastify 中使用 ajv-formats 吗?或者你能帮帮我吗?
提前致谢!
【问题讨论】:
-
你运行的是什么版本?
-
我现在正在运行 fastify@3.9.2
-
您能添加一些架构吗?因为我有一个使用此插件的工作示例,但无法复制您的错误
-
错误没有路由也没有,例如,使用这段代码,我得到错误:`` async function run (): Promise
{ server.addHook('onRoute', (options) => console.log(options)) await server.register(helmet) await server.register(cors) return server.listen(3000, 'localhost') } ``` 使用这段代码,我得到了错误
标签: javascript node.js ajv fastify