Swagger UI Express - 无法获取 /docs/

Swagger UI Express - Cannot GET /docs/

我实现了一个集成了 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/

当然 /api 里面已经有 swagger.yaml 文件了。请问这个问题有什么解决办法吗?

发生这种情况是因为您正在收听

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc))

并尝试访问 http://localhost:8080/docs。您可以将上面的行更改为: app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc))