我尝试使用fastify/swagger来构建我的API文档,它工作正常,这是我的代码。
问题是,它只能得到/route 2,但不能得到/route 1。有什么建议吗?
'use strict'
const fastify = require('fastify')()
// Define a sample route
fastify.get('/route1', async (request, reply) => {
return { route1: 'world' };
});
const start = async () => {
try {
await fastify.register(require('@fastify/swagger'), {
// openapi 3.0.3 options
openapi: {
...
},
})
// Define a sample route
fastify.get('/route2', async (request, reply) => {
return { route2: 'world' };
});
// Define a sample route
fastify.get('/doc', opts, async (request, reply) => {
reply.send(fastify.swagger())
});
await fastify.ready()
await fastify.listen({ port: 3000 });
console.log(`Server listening on ${fastify.server.address().port}`);
} catch (err) {
console.log(err);
process.exit(1);
}
};
start();
1条答案
按热度按时间iszxjhcz1#
问题是,它只能得到/route 2,但不能得到/route 1。有什么建议吗?
fastify-swagger
在引擎盖下使用onRoute
挂钩。这意味着钩子函数在事件发生时同步执行。* 这在我的Fastify书中有详细解释。*因此,在您的代码示例中,您将在注册和等待插件之前添加路由:
await fastify.register(require('@fastify/swagger')
。因此,在向
fastify
对象示例添加任何路由之前,必须先注册fastify-swagger
。此外,您创建的路由:
是获取文档的正确方法,但由于您使用的是
reply.send()
,因此处理程序可能不是async
,因为此文档:https://fastify.dev/docs/latest/Reference/Routes/#promise-resolution