node的swagger現在也用上了注釋型的文檔,和java的有點類似。主要步驟就兩個:swagger配置和注釋生成文檔

話不多說,直接開始
安裝
// koa2-swagger-ui UI視圖組件 swagger-jsdoc 識別寫的 /***/ 轉 json npm install koa2-swagger-ui swagger-jsdoc --save
直接安裝即可
配置
新建 swagger.js 文件,位置放哪都行,只要自己能找到,我放在了根目錄,和 packages.js 同級
const router = require('koa-router')() //引入路由函數 const swaggerJSDoc = require('swagger-jsdoc') const path = require('path') const swaggerDefinition = { info: { title: 'blog項目訪問地址', version: '1.0.0', description: 'API', }, host: 'localhost:8000',// 想着改這里,如果不修改,那么接口文檔訪問地址為:localhost:8000/swagger basePath: '/' // Base path (optional) }; const options = { swaggerDefinition, apis: [path.join(__dirname, './routes/*.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
在 app.js 中新增配置
const swagger = require('./swagger') // 存放swagger.js的位置,可以自行配置,我放在了根目錄 const { koaSwagger } = require('koa2-swagger-ui') // 接口文檔配置 app.use(swagger.routes(), swagger.allowedMethods()) app.use(koaSwagger({ routePrefix: '/swagger', // 接口文檔訪問地址 swaggerOptions: { url: '/swagger.json', // example path to json 其實就是之后swagger-jsdoc生成的文檔地址 } }))
啟動項目,訪問項目接口地址 + swagger ,我的地址是 http://localhost:8000/swagger

添加注釋生成文檔
1、學習 YAML 語言教程
2、根據 swagger 文檔說明,添加注釋
參考: https://blog.csdn.net/qq_38734862/article/details/107715579