Nodejs Koa2框架中使用Swagger

yarn add koa2-swagger-ui swagger-jsdoc

server.js

const Koa = require('koa')
const app = new Koa()
const {koaSwagger} = require('koa2-swagger-ui') 
const swaggerRouter = require('./routes/swagger') 

// ......


app.use(swaggerRouter.routes()).use(swaggerRouter.allowedMethods())
const swaggerOption = {
   routePrefix: '/swagger/index.html', // host at /swagger instead of default /docs
   swaggerOptions: {
        url: '/swagger/swagger.json' // example path to json 其实就是之后swagger-jsdoc生成的文档地址
   }
 }
app.use(koaSwagger(swaggerOption))
app.listen(3000)

./routes/swagger.js

const Router = require('koa-router')
const path = require('path')
const swaggerJSDoc = require('swagger-jsdoc')
const router = new Router({
    prefix: '/swagger' // 路由前缀
})
const swaggerDefinition = {
    info: {
        title: 'API 接口',
        version: 'v1'
    }
}
const options = {
    swaggerDefinition,
    apis: [path.join(__dirname, './docs/*.js')] // 写有注解的router的存放地址, 最好     path.join()
}
const swaggerSpec = swaggerJSDoc(options)
// 通过路由获取生成的注解文件
router.get('/swagger.json', async function (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: "获取数据列表" 
 *     produces: 
 *       - application/json 
 *     responses: 
 *       200:
 *         description: 获取数据列表 
 * */

配置成功

访问地址 http://127.0.0.1/swagger/inde...

你可能感兴趣的:(Nodejs Koa2框架中使用Swagger)