nodejs koa integration swagger

install swagger


npm install swagger-jsdoc koa2-swagger-ui --save

New swagger.js


const router = require('koa-router')()
const jsdoc = require('swagger-jsdoc')
const path = require('path')

const swaggerDefinition = {
    
    
    info: {
    
    
        title: 'API文档',
        version: '1.0',
        description: '文档',
    },
    host: 'localhost:8000',//localhost:8000/swagger
    basePath: '/'
};
const options = {
    
    
    swaggerDefinition,
    apis: ['./controller/*.js'],
};
const swaggerSpec = jsdoc(options)
// 通过路由获取生成的注解文件
router.get('/swagger.json', async function (ctx) {
    
    
    ctx.set('Content-Type', 'application/json');
    ctx.body = swaggerSpec;
})
module.exports = router

Modify app.js


const swagger = require('./service/swagger.js')
const {
    
     koaSwagger } = require('koa2-swagger-ui')

app.use(swagger.routes(), swagger.allowedMethods())
app.use(koaSwagger({
    
    
  routePrefix: '/swagger', // api文档访问地址
  swaggerOptions: {
    
    
    url: '/swagger.json', // example path to json
  }
}))

interface configuration

/**
 * @swagger
 * /getNum:
 *   get:
 *     tags:
 *       - tes
 *     summary: 测试
 *     parameters:
 *       - name: num
 *         description: 数量
 *         type: integer
 */
router.get('/getNum', async (ctx, next) => {
    
    
	console.log(ctx.query.num)
	ctx.body = ctx.query.num
})

View the effect

http://localhost:3000/swagger
Please add a picture description

Guess you like

Origin blog.csdn.net/weixin_42704356/article/details/123688955