当前位置: 首页 > 后端技术 > Node.js

在NodejsKoa2框架中使用Swagger

时间:2023-04-03 18:00:46 Node.js

yarnaddkoa2-swagger-uiswagger-jsdocserver.jsconstKoa=require('koa')constapp=newKoa()const{koaSwagger}=require('koa2-swagger-ui')constswaggerRouter=require('./routes/swagger')//......app.use(swaggerRouter.routes()).use(swaggerRouter.allowedMethods())constswaggerOption={routePrefix:'/swagger/index.html',//hostat/swaggerinsteadofdefault/docsswaggerOptions:{url:'/swagger/swagger.json'//json的示例路径实际上是swagger-jsdoc生成的文档地址}}app.use(koaSwagger(swaggerOption))app.listen(3000)./routes/swagger.jsconstRouter=require('koa-router')constpath=require('path')constswaggerJSDoc=require('swagger-jsdoc')constrouter=newRouter({前缀:'/swagger'//路由前缀})constswaggerDefinition={info:{title:'APIInterface',version:'v1'}}constoptions={swaggerDefinition,apis:[path.join(__dirname,'./docs/*.js')]//注释路由的存储地址,最好是path.join()}constswaggerSpec=swaggerJSDoc(options)//通过路由获取生成的注解文件router.get('/swagger.json',asyncfunction(ctx){ctx.set('Content-Type','application/json')ctx.body=swaggerSpec})module.exports=router./routes/doc/api.js/***@swagger*/api/list:*get:*description:获取数据列表*tags:[API]*summary:"获取数据List"*produces:*-application/json*responses:*200:*description:获取数据列表**/配置成功访问地址http://127.0.0.1/swagger/inde...