安装环境:CentOS Linux release 7.6.1810 (Core)
安装Node.js的npm工具环境
curl -sL https://rpm.nodesource.com/setup_12.x | bash -
yum install nodejs -y
安装完成后查看版本
node -v
npm -v
下载安装【Swagger-Editor】
wget https://github.com/swagger-api/swagger-editor/archive/v3.14.0.tar.gz
tar -xf v3.14.0.tar.gz
安装 node.js HttpServer
npm install -g http-server
安装完成后, 在 swagger-editor-3.14.0同级目录中, 启动服务
http-server -p 7089 swagger-editor-3.14.0
访问http://IP:7089/,注意防火墙7089端口,能成功访问即开启成功。
下载安装【安装 Swagger-UI】
wget https://github.com/swagger-api/swagger-ui/archive/v3.34.0.tar.gz
tar -xf v3.34.0.tar.gz
初始化 node ,创建 package.json文件
最终产生一个package.json文件,在/var/www/swagger/目前中。
npm init
[root@localhost swagger]# npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (swagger) swagger-ui
version: (1.0.0) 3.34.0
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /var/www/swagger/package.json:
{
"name": "swagger-ui",
"version": "3.34.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
[root@localhost swagger]#
安装 express
npm install express --save
创建index.js文件,并写入如下内容
vim index.js
index.js内容,swagger-ui-3.34.0/dist/ 是swagger-ui的项目路径
var express = require('express');
var app = express();
var http = require('http');
app.use('/static', express.static('swagger-ui-3.34.0/dist/'));
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(7090, function () {
console.log('Example app listening on port 7090!');
});
启动 index.js,
node index.js
访问http://IP:7090/,注意防火墙7090端口,能成功访问即开启成功,7090端口可在index.js中修改。
两个地址均能成功访问,则swagger搭建完成。
使用方法:
在swagger-editor编写我们自己的接口文档后,点击左上角"File"-"convert and save as json"保存到本地,默认文件名为swagger.json,可自由修改。
将swagger.json上传到swagger-ui-3.34.0/dist/目录中,并修改该目录中index.html文件
将原内容
url: "https://petstore.swagger.io/v2/swagger.json"
替换为新内容
url: "/static/swagger.json",
刷新http://IP:7090/static/index.html页面,即可看到API文档。