ubuntu

Ubuntu Swagger UI如何自定义

小樊
35
2025-03-28 09:04:12
栏目: 智能运维

在Ubuntu上自定义Swagger UI可以通过多种方法实现,以下是一些常见的方法:

使用Docker安装和自定义Open WebUI

使用Express框架自定义Swagger UI

  1. 安装Node.js和npm

    curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
  2. 创建Express应用: 创建一个目录并进入该目录,然后初始化npm项目并安装Express和其他必要的中间件:

    mkdir my-swagger-ui
    cd my-swagger-ui
    npm init -y
    npm install express body-parser cookie-parser multer
    
  3. 配置Express应用: 编辑 index.js 文件,添加以下内容:

    const express = require('express');
    const app = express();
    const path = require('path');
    
    app.use('/swagger', express.static(path.join(__dirname, 'node_modules/swagger-ui/dist')));
    
    app.get('/', function (req, res) {
      res.sendFile(path.join(__dirname, 'node_modules/swagger-ui/dist/index.html'));
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, function () {
      console.log(`App is running on port ${PORT}`);
    });
    
  4. 启动服务器

    node index.js
    
  5. 访问Swagger UI: 打开浏览器,访问 http://localhost:3000/swagger 即可看到自定义的Swagger UI界面。

使用Webjars打包前端资源

  1. 下载Swagger UI: 从Swagger GitHub仓库下载最新的Swagger UI源码并解压。

  2. 构建项目: 使用Webjars将前端资源打包成jar包:

    mvn package
    
  3. 配置Express应用: 将生成的jar包添加到你的Express应用中,并配置静态资源路径:

    const express = require('express');
    const app = express();
    const path = require('path');
    
    app.use('/swagger', express.static(path.join(__dirname, 'node_modules/swagger-ui-dist')));
    
    app.get('/', function (req, res) {
      res.sendFile(path.join(__dirname, 'node_modules/swagger-ui-dist/index.html'));
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, function () {
      console.log(`App is running on port ${PORT}`);
    });
    
  4. 启动服务器

    node index.js
    
  5. 访问Swagger UI: 打开浏览器,访问 http://localhost:3000/swagger 即可看到自定义的Swagger UI界面。

通过以上方法,你可以在Ubuntu上成功自定义Swagger UI,选择适合你项目需求的方式进行操作即可。

0
看了该问题的人还看了