我通过集成Swagger文档实现了一个简单的服务器。我的简单代码如下
const http = require('http');
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const bodyParser = require('body-parser');
const YAML = require('yamljs');
const serverPort = 8080;
const app = express();
const swaggerDoc = YAML.load('./api/swagger.yaml');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc));
app.use(bodyParser.urlencoded({
extended: false,
}));
app.use(bodyParser.json());
http.createServer(app).listen(serverPort, function () {
console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort);
});
执行node server.js
后,我访问http://localhost:8080/docs并得到
Cannot GET /docs/
[我当然已经在swagger.yaml
中包含/api
文件。请解决这个问题吗?
发生这种情况是因为您正在听
app.use('/ api-docs',swaggerUi.serve,swaggerUi.setup(swaggerDoc))>] >> 并尝试访问http://localhost:8080/docs。将上面的行更改为:app.use('/ docs',swaggerUi.serve,swaggerUi.setup(swaggerDoc))