在Debian环境下部署Swagger的流程通常涉及以下几个步骤:
sudo apt update
sudo apt install nodejs npm
sudo npm install -g swagger-ui-express
创建一个简单的Express应用:
app.js
的文件。const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 读取Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// 使用swagger-ui-express中间件
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
创建Swagger文档:
swagger.yaml
的文件,并添加你的API文档。例如:swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI on Debian
version: '1.0.0'
host: localhost:3000
basePath: /
schemes:
- http
paths:
/users:
get:
summary: List all users
responses:
'200':
description: An array of users
启动应用:
node app.js
访问Swagger UI:
http://localhost:3000/api-docs
,你应该能够看到Swagger UI界面,并且可以浏览和测试你的API。配置Nginx(可选):
sudo apt install nginx
sudo nano /etc/nginx/sites-available/swagger-ui
server {
listen 80;
server_name your_domain.com;
location /api-docs {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host host;
proxy_cache_bypass http_upgrade;
}
}
sudo ln -s /etc/nginx/sites-available/swagger-ui /etc/nginx/sites-enabled
sudo systemctl restart nginx
现在,你的Swagger UI应用应该可以通过 http://your_domain.com/api-docs
访问了。
以上步骤提供了一个基本的Swagger UI配置。根据你的具体需求,你可能需要调整Swagger定义文件以匹配你的API,并可能需要安装额外的依赖项或进行其他配置。