要在 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。