Ubuntu安装Swagger UI

环境

  • 操作系统: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值