在Ubuntu上使用Swagger调试API的完整流程
在Ubuntu上调试Swagger前,需先安装Node.js和npm(Swagger Editor/UI的运行依赖)。打开终端,执行以下命令:
sudo apt update
sudo apt install -y nodejs npm
安装完成后,通过node -v和npm -v验证安装是否成功。
Swagger Editor支持在线编写、预览和调试Swagger规范(YAML/JSON格式)。通过npm全局安装:
npm install -g swagger-editor
安装完成后,启动Editor:
swagger-editor
默认会在http://localhost:9000启动,浏览器访问即可进入编辑界面。
Swagger UI用于可视化测试API接口。通过npm全局安装:
npm install -g swagger-ui-express
若需单独启动Swagger UI(非集成到Express项目),可使用以下命令(需提前下载Swagger UI源码):
npm install -g swagger-ui
swagger-ui
默认会在http://localhost:8080启动。
Swagger调试的核心是Swagger规范文件(swagger.yaml或swagger.json),可通过以下两种方式获取:
springfox-swagger2、swagger-jsdoc)自动生成。若需将Swagger UI集成到自己的Express应用中,需创建app.js文件并添加以下代码:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
const port = process.env.PORT || 3000;
// 读取Swagger规范文件(需提前创建swagger.yaml)
const swaggerDocument = YAML.load('./swagger.yaml');
// 挂载Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(port, () => {
console.log(`Swagger UI is running at http://localhost:${port}/api-docs`);
});
启动Express应用后,通过http://localhost:3000/api-docs访问Swagger UI。
http://localhost:3000/api-docs,Swagger UI会自动加载swagger.yaml;swagger.yaml或输入远程URL(如http://your-server/swagger.yaml)。GET /users),点击接口名称左侧的Try it out按钮;若需自动处理授权(如Bearer Token)或修改请求数据,可在Swagger UI目录下创建custom.js文件,编写自定义函数(如自动添加Token),并通过InjectJavascript机制注入到Swagger UI中间件中。
若需调试后端代码(如Node.js服务),可使用VS Code的调试功能:
launch.json配置文件(位于.vscode目录):{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js",
"skipFiles": ["<node_internals>/**"]
}
]
}
node --inspect-brk app.js,然后在VS Code中按下F5开始调试。若不想手动安装依赖,可使用Docker快速启动Swagger Editor/UI:
# 拉取Swagger Editor镜像
docker pull swaggerapi/swagger-editor:v4.6.0
# 运行Editor容器(映射端口38080到宿主机8080)
docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
# 拉取Swagger UI镜像
docker pull swaggerapi/swagger-ui:v4.15.5
# 运行UI容器(映射端口38081到宿主机8080)
docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
访问http://localhost:38080(Editor)或http://localhost:38081(UI)即可使用。
404错误,需检查防火墙设置(允许对应端口,如sudo ufw allow 3000);Ctrl+Z暂停进程,建议使用Ctrl+C终止,防止进程在后台残留。