如何在CentOS上使用Swagger Editor
导读:在CentOS上使用Swagger Editor的步骤 1. 安装Node.js和npm Swagger Editor依赖Node.js环境,需先安装Node.js(包含npm包管理器)。 方法一:通过NodeSource仓库安装(推荐)...
在CentOS上使用Swagger Editor的步骤
1. 安装Node.js和npm
Swagger Editor依赖Node.js环境,需先安装Node.js(包含npm包管理器)。
- 方法一:通过NodeSource仓库安装(推荐)
运行以下命令添加NodeSource仓库并安装Node.js(以Node.js 14.x为例):curl -sL https://rpm.nodesource.com/setup_14.x | sudo -E bash - sudo yum install -y nodejs
- 验证安装:
安装完成后,执行以下命令确认版本(需显示版本号即为成功):node -v # 查看Node.js版本 npm -v # 查看npm版本
2. 安装Swagger Editor
有两种常见方式安装Swagger Editor:
- 方式一:全局安装(快速启动)
使用npm全局安装Swagger Editor及其依赖的HTTP服务器:sudo npm install -g swagger-editor http-server
- 方式二:从源码安装(自定义配置)
若需要修改Editor源码,可克隆官方仓库并本地安装:git clone https://github.com/swagger-api/swagger-editor.git cd swagger-editor npm install -g http-server # 安装HTTP服务器
3. 启动Swagger Editor
- 全局安装的启动方式:
直接运行以下命令启动Editor服务,默认监听8080端口:swagger-editor
- 源码安装的启动方式:
进入项目目录,使用HTTP服务器启动:cd /path/to/swagger-editor http-server -p 8080 # 指定端口(如8080)
- 访问Editor:
启动后,在浏览器中输入http://localhost:8080
(若为远程服务器,替换为IP地址),即可打开Swagger Editor界面。
4. 使用Swagger Editor编写/编辑文档
- 新建文档:
点击界面左侧的“+”号,选择“Create New”创建空白文档,或通过“Import File”上传现有Swagger JSON/YAML文件。 - 编辑文档:
在右侧编辑区编写API定义(支持YAML或JSON格式),左侧实时预览生成的文档结构。 - 保存文档:
编辑完成后,点击顶部菜单栏的“File”→“Save As”,将文档保存为swagger.json
或swagger.yaml
格式。
5. (可选)配置Swagger UI查看自定义文档
若需将Swagger Editor编写的文档导入Swagger UI进行可视化展示,需完成以下步骤:
- 安装Swagger UI:
克隆官方仓库并安装依赖:git clone https://github.com/swagger-api/swagger-ui.git cd swagger-ui npm install
- 配置自定义文档路径:
进入Swagger UI的dist
目录,修改index.html
文件,将默认的Swagger Petstore文档URL替换为自己的文档路径(如/static/your-swagger.json
):// 修改前(默认Petstore文档) url: "https://petstore.swagger.io/v2/swagger.json", // 修改后(指向本地自定义文档) url: "/static/your-swagger.json",
- 启动Swagger UI:
创建静态文件目录并复制文档,启动HTTP服务器:mkdir -p /opt/swagger/public cp -r swagger-ui/dist/* /opt/swagger/public/ cp /path/to/your-swagger.json /opt/swagger/public/ cd /opt/swagger/public http-server -p 3000
- 访问Swagger UI:
在浏览器中输入http://localhost:3000
,即可查看自定义的API文档。
注意事项
- 防火墙设置:若为远程访问,需开放对应端口(如8080、3000),执行以下命令:
sudo firewall-cmd --permanent --add-port=8080/tcp sudo firewall-cmd --reload
- 版本兼容性:建议使用Node.js 12.x及以上版本,避免依赖冲突。
- 权限问题:全局安装时使用
sudo
,本地安装无需sudo
(推荐)。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何在CentOS上使用Swagger Editor
本文地址: https://pptw.com/jishu/727407.html