Fastify集成@fastify/swagger报错:fastify.swagger is not a function
解决Fastify中@fastify/swagger的TypeError问题
启动Fastify应用时出现如下错误:
fastify_app@1.0.0 start D:\dev\fastify_app node app.js {"level":30,"time":1666146720089,"pid":13484,"hostname":"Dell","msg":"Server listening at http://127.0.0.1:3000"} {"level":30,"time":1666146720113,"pid":13484,"hostname":"Dell","msg":"Server listening at http://[::1]:3000"} D:\dev\fastify_app\app.js:15 fastify.swagger() ^ TypeError: fastify.swagger is not a function at D:\dev\fastify_app\app.js:15:15 at D:\dev\fastify_app\node_modules\fastify\lib\server.js:67:11 at Object.cb (D:\dev\fastify_app\node_modules\fastify\lib\server.js:128:15) at Server.wrap (D:\dev\fastify_app\node_modules\fastify\lib\server.js:166:21) at Object.onceWrapper (events.js:519:28) at Server.emit (events.js:400:28) at emitListeningNT (net.js:1365:10) at processTicksAndRejections (internal/process/task_queues.js:81:21) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! fastify_app@1.0.0 start: `node app.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the fastify_app@1.0.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Dell\AppData\Roaming\npm-cache\_logs\2022-10-19T02_32_00_228Z-debug.log
问题原因
- Swagger插件未关联主Fastify实例:你的
swagger.js中创建了独立的Fastify实例并注册Swagger,没有将插件绑定到应用的主实例上,导致主实例不存在swagger()方法。 - 多余的手动调用:@fastify/swagger注册后会自动生成文档路由,不需要在
listen回调中手动调用fastify.swagger()。
修正方案
修改swagger.js
改为导出符合Fastify插件规范的函数,接收主实例并完成Swagger注册:
module.exports = async function (fastify, opts) { await fastify.register(require("@fastify/swagger"), { routePrefix: "/docs", exposeRoute: true, swagger: { info: { title: "Fastify API", description: "Building a blazing fast REST API with Node.js, MongoDB, Fastify and Swagger", version: "1.0.0", }, externalDocs: { url: "https://swagger.io", description: "Find more info here", }, host: "localhost:3000", schemes: ["http"], consumes: ["application/json"], produces: ["application/json"], }, }); };
修改app.js
在主实例中注册Swagger插件,同时移除不必要的fastify.swagger()调用:
const fastify = require("fastify")({logger:true}); require("dotenv").config(); const PORT = process.env.PORT; // 先注册Swagger插件 fastify.register(require('./swagger')); fastify.register(require("./app/Routes/users.route")); fastify.get("/", (req, res) => { res.send("Hello world"); }); const start = async () => { try { await fastify.listen({ port: PORT }); console.log(`server is listening on port ${PORT}`); } catch (error) { console.log(error); process.exit(1); } }; start();
验证
启动应用后,访问http://localhost:3000/docs即可查看Swagger文档界面,TypeError错误会消失。
内容的提问来源于stack exchange,提问作者Vamsi
相关产品推荐
相关产品推荐

