swagger配置
xp 2020-10-30 swagger
安装 环境:
npm install swagger-jsdoc swagger-ui-express --save
1
const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express')
const swaggerJSDoc = require('swagger-jsdoc')
const path = require('path')
// 配置 swagger-jsdoc
const options = {
definition: {
// swagger 采用的 openapi 版本 不用改
openapi: '3.0.0',
// swagger 页面基本信息 自由发挥
info: {
title: 'Express Template',
version: '1.0.0',
}
},
// 重点,指定 swagger-jsdoc 去哪个路由下收集 swagger 注释
apis: [path.join(__dirname, './router/*.js')]
}
const swaggerSpec = swaggerJSDoc(options);
// 开放 swagger 相关接口,
app.get('/swagger.json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
// 使用 swaggerSpec 生成 swagger 文档页面,并开放在指定路由
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.listen(3000, () => {
console.log('服务启动成功:' + `http://localhost:3000/`)
});
/**
* @swagger
* /hello:
* get:
* tags:
* - 测试
* summary: GET 测试
* description: 用于测试基础 GET 请求的接口
* parameters:
* - name: page
* responses:
* 200:
* description: 【成功】 返回 ok
*/
app.get('/hello', (req, res) => {
res.send('ok')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54