共计 1195 个字符,预计需要花费 3 分钟才能阅读完成。
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…
正文完