如何自定义CentOS Swagger UI
要在 CentOS 上自定义 Swagger UI,您可以遵循以下步骤:
-
安装 Node.js 和 npm: 在 CentOS 上安装 Node.js 和 npm。您可以使用以下命令安装它们:
sudo yum install -y nodejs npm -
安装 Swagger UI: 使用 npm 安装 Swagger UI Express。在终端中运行以下命令:
sudo npm install swagger-ui-express -
创建一个简单的 Express 应用程序: 在您的 CentOS 服务器上创建一个新的目录,并在其中创建一个名为
app.js的文件。将以下代码粘贴到app.js文件中:const express = require('express'); const swaggerUi = require('swagger-ui-express'); const YAML = require('yamljs'); const app = express(); const port = process.env.PORT || 8080; // 读取 Swagger 文档 const swaggerDocument = YAML.load('./swagger.yaml'); // 将 Swagger 文档添加到 Express 应用程序 app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); // 启动 Express 应用程序 app.listen(port, () => { console.log(`Server is running at http://localhost:${ port} `); } ); -
创建 Swagger 文档: 在项目目录中创建一个名为
swagger.yaml的文件。在此文件中,定义您的 API 文档。例如:swagger: '2.0' info: title: Sample API description: A sample API to demonstrate Swagger UI customization on CentOS version: '1.0.0' host: localhost:8080 basePath: /api-docs schemes: - http paths: /users: get: summary: List all users responses: '200': description: An array of users schema: type: array items: $ref: '#/definitions/User' definitions: User: type: object properties: id: type: integer format: int64 name: type: string email: type: string format: email -
运行应用程序: 在终端中,导航到项目目录并运行以下命令以启动应用程序:
node app.js -
自定义 Swagger UI: 要自定义 Swagger UI,您可以修改
app.js文件中的代码。例如,您可以更改 UI 的主题、布局和样式。以下是一些可用的选项:-
更改主题:访问 Swagger UI Themes 页面,选择一个主题并将其下载到您的项目中。然后,在
app.js文件中,使用swaggerUi.setup()函数的deepLinking选项启用主题:const ui = swaggerUi.serve; const setup = swaggerUi.setup(swaggerDocument, { deepLinking: true, presets: [ swaggerUi.presets.apis, swaggerUi.presets.promises, swaggerUi.presets.oauth2, require('./path/to/your/theme').default ], plugins: [], layout: "StandaloneLayout" } ); app.use('/api-docs', ui, setup); -
自定义 CSS 和 JavaScript:在项目目录中创建一个名为
custom.css的文件,并在其中添加您的自定义 CSS 样式。然后,在app.js文件中,使用swaggerUi.setup()函数的customCssUrl选项指定 CSS 文件的路径:const setup = swaggerUi.setup(swaggerDocument, { customCssUrl: '/path/to/your/custom.css' } );
类似地,您可以创建一个名为
custom.js的文件,并在其中添加您的自定义 JavaScript 代码。然后,在app.js文件中,使用swaggerUi.setup()函数的customJsUrl选项指定 JavaScript 文件的路径:const setup = swaggerUi.setup(swaggerDocument, { customJsUrl: '/path/to/your/custom.js' } ); -
-
重新启动应用程序: 在终端中,导航到项目目录并运行以下命令以重新启动应用程序:
node app.js
现在,您的 CentOS 上的自定义 Swagger UI 应用程序已准备好使用。访问 http://localhost:8080/api-docs 查看自定义后的 Swagger UI。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何自定义CentOS Swagger UI
本文地址: https://pptw.com/jishu/736993.html
