Ubuntu上Swagger文档怎么查看
导读:在 Ubuntu 上查看 Swagger 文档的常用方式 使用 Docker 快速启动 Swagger UI 在现有项目中集成 Swagger UI Express 并访问 /api-docs 使用 Swagger Editor 在线或本...
在 Ubuntu 上查看 Swagger 文档的常用方式
- 使用 Docker 快速启动 Swagger UI
- 在现有项目中集成 Swagger UI Express 并访问 /api-docs
- 使用 Swagger Editor 在线或本地查看/编辑 swagger.yaml 或 swagger.json
- 直接用浏览器打开本地或远程的 swagger.json/swagger.yaml 文件进行预览(部分浏览器可解析展示)
方式一 Docker 运行 Swagger UI
- 安装 Docker(如未安装):
- sudo apt update
- sudo apt install docker.io
- 启动容器并挂载本地文档(推荐,便于直接查看你的文件):
- 将当前目录挂载到容器的 /app,并通过环境变量指定文档:
- docker run --rm -p 8080:8080 -e SWAGGER_JSON=/app/swagger.json -v $(pwd):/app swaggerapi/swagger-ui-express
- 如你的文件是 YAML,可先转换为 JSON,或改用能直接服务 YAML 的镜像/方案。
- 将当前目录挂载到容器的 /app,并通过环境变量指定文档:
- 访问:打开浏览器访问 http://localhost:8080,即可看到 Swagger UI 页面。
- 说明:也可不挂载直接运行 docker run -p 8080:8080 swaggerapi/swagger-ui-express,再在 UI 顶部的输入框填写你的文档 URL(如 http://服务器IP:端口/swagger.json)。
方式二 在现有 Node.js 项目中集成 Swagger UI Express
- 安装依赖:
- sudo apt update
- sudo apt install nodejs npm
- npm install swagger-ui-express yamljs
- 示例代码(app.js):
- const express = require(‘express’);
const swaggerUi = require(‘swagger-ui-express’);
const YAML = require(‘yamljs’);
const swaggerDocument = YAML.load(‘./swagger.yaml’);
// 或 swagger.json
const app = express();
app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(
Server running on ${ PORT}));
- const express = require(‘express’);
const swaggerUi = require(‘swagger-ui-express’);
const YAML = require(‘yamljs’);
const swaggerDocument = YAML.load(‘./swagger.yaml’);
// 或 swagger.json
const app = express();
app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(
- 启动服务:node app.js
- 访问:打开浏览器访问 http://localhost:3000/api-docs。
方式三 使用 Swagger Editor 查看或编辑
- 在线使用:打开 Swagger Editor 官网的 Live Demo,在页面中导入或编辑你的 swagger.yaml/swagger.json。
- 本地使用:
- 克隆并启动:git clone https://github.com/swagger-api/swagger-editor.git & & cd swagger-editor & & npm install & & npm start
- 访问:浏览器打开 http://localhost:8080,在编辑器或页面输入框加载你的规范文件 URL 进行预览。
常见问题与排查
- 访问被拒绝或页面空白:检查服务是否监听 0.0.0.0 而非仅 127.0.0.1;云服务器需确保安全组/防火墙放行对应端口(如 8080、3000)。
- 文件加载失败:确认 YAML/JSON 语法正确;使用 Docker 挂载时注意路径映射与文件名一致;跨域问题可改用同域服务或反向代理。
- 文档格式:Swagger UI 支持 JSON 和部分 YAML;若使用 YAML,确保解析库已安装(如 yamljs),或转换为 JSON 再加载。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Ubuntu上Swagger文档怎么查看
本文地址: https://pptw.com/jishu/763837.html
