首页 > 解决方案 > Swagger UI Express - 无法获取 /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/

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

标签: node.jsswagger-ui

解决方案


这是因为你在听

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

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


推荐阅读