环境
- 操作系统:Ubuntu 22.04
- node 16.15.1
- npm 8.11.0
安装Swagger UI
方法0:官网在线的 Swagge UI
https://swagger.io/tools/swagger-ui/ 页面上有一个 Live Demo
按钮,点击就能打开一个在线的Swagger UI 。
方法1:从git项目下载release
https://github.com/swagger-api/swagger-ui
,点击页面右边的 Releases
链接,可以看到,各个版本的release都只有源码下载。
比如下载 v4.12.0.zip
。解压后,进入 dist
目录,运行 http-server
。
打开浏览器,访问 http://localhost:8080/
:
方法2:克隆git项目
git clone git@github.com:swagger-api/swagger-ui.git
然后方法同上。
方法3:从npm安装(没成功)
npm i -g swagger-ui
在 /home/ding/Downloads/node-v16.15.1-linux-x64/lib/node_modules
目录下生成了 swagger-ui
目录。
但是在 swagger-ui/dist
目录里面,并没有 index.html
文件。
这里面一定缺了一些东西,有待研究。
方法4:创建自己的npm项目
新建一个文件夹 temp0620
,然后进入该文件夹。
npm init
,生成 package.json
文件。
npm i express
,安装 express
。注意:如果加 -g
,下面的步骤里会报错说找不到 express
,估计需要类似Java的 import
一下。
复制前面方法中下载的 dist
目录到当前目录下。
创建文件 index.js
如下:
var express = require('express');
var app = express();
app.use('/root', express.static('dist'));
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
整体文件结构如下:
➜ temp0620 ls
dist index.js node_modules package.json
node index.js
启动server。
打开浏览器,访问 http://localhost:3000/root/index.html
:
使用Swagger UI
Swagger UI的用法非常简单。它默认打开的是 https://petstore.swagger.io/v2/swagger.json
。这是在 swagger-initializer.js
里面配置的。可以把它改为你想要默认打开的文件。
window.onload = function() {
//<editor-fold desc="Changeable Configuration Block">
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
window.ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
//</editor-fold>
};
当然,不修改也无所谓,可以在打开页面后,选择想要打开的文件。
比如,从 swagger-editor
导出 swagger.yaml
文件,复制到 dist
目录下。
重启服务器,在页面输入框输入 swagger.yaml
,然后点击 Explore
按钮,如下:
现在打开的就是指定的文件了。
注意:直接拖文件到输入框过来是不行的:
file://
开头的地址不行,这与 CORS
有关,搜一下这个问题,应该有办法能解决,没仔细研究。
参考
- https://swagger.io/docs/open-source-tools/swagger-ui
- https://github.com/swagger-api/swagger-ui
- https://www.likecs.com/show-203722236.html