温馨提示×

如何在Linux中使用Swagger UI

小樊
40
2025-02-25 07:20:47
栏目: 智能运维
Linux服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Linux中使用Swagger UI可以通过以下几种方法实现:

使用Docker容器部署

  1. 安装Docker: 如果你还没有安装Docker,请先安装它。在Ubuntu上,可以使用以下命令安装Docker:

    sudo apt update
    sudo apt install -y docker.io
    sudo systemctl start docker
    sudo systemctl enable docker
    
  2. 拉取并运行Swagger UI容器

    docker pull swaggerapi/swagger-ui:v4.6.0
    docker run -d -p 38080:8080 swaggerapi/swagger-ui:v4.6.0
    

    这将启动Swagger UI容器,默认情况下可以通过访问http://localhost:38080来查看。

使用npm在Node.js项目中安装和部署

  1. 安装Node.js和npm: 如果你还没有安装Node.js和npm,可以使用以下命令安装:

    curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
  2. 创建并启动一个简单的Express应用

    mkdir my-swagger-app
    cd my-swagger-app
    npm init -y
    npm install express
    
  3. 创建index.js文件

    var express = require('express');
    var app = express();
    app.use('/swagger', express.static('node_modules/swagger-ui/dist'));
    app.listen(3000, function () {
        console.log('App is running on port 3000');
    });
    
  4. 启动应用

    node index.js
    
  5. 访问Swagger UI: 打开浏览器,访问http://localhost:3000/swagger,你应该能看到Swagger UI的界面。

使用HTTP服务器部署

  1. 下载Swagger UI: 你可以从Swagger的GitHub仓库下载最新版本的Swagger UI:https://github.com/swagger-api/swagger-ui

  2. 解压文件

    unzip v2.4.27.zip
    
  3. 创建一个简单的HTTP服务器

    mkdir public
    cp -r swagger-ui/dist/* public/
    
  4. 创建index.html文件: 在public目录下创建一个index.html文件,内容如下:

    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="swagger-ui.css">
    </head>
    <body>
        <div id="swagger-ui"></div>
        <script src="swagger-ui.js"></script>
        <script>
            window.onload = function() {
                // Begin Swagger UI call region
                const ui = SwaggerUIBundle({
                    url: "http://petstore.swagger.io/v2/swagger.json",
                    dom_id: '#swagger-ui',
                    deepLinking: true,
                    presets: [
                        SwaggerUIBundle.presets.apis,
                        SwaggerUIStandalonePreset
                    ],
                    plugins: [
                        SwaggerUIBundle.plugins.DownloadUrl
                    ],
                    layout: "StandaloneLayout"
                });
                // End Swagger UI call region
                window.ui = ui;
            }
        </script>
    </body>
    </html>
    
  5. 启动HTTP服务器

    node public/index.html
    
  6. 访问Swagger UI: 打开浏览器,访问http://localhost:8080,你应该能看到Swagger UI的界面。

通过以上步骤,你可以在Linux系统中成功部署和使用Swagger UI。选择适合你的方法进行操作即可。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在Linux中使用Swagger进行测试

0