Swagger 在 app.use 中呈现但不在 app.get 中呈现

Swagger renders in app.use but not in app.get

我正在尝试使用 swagger-ui-express 呈现 Swagger 文档。但是只有在使用 app.use 时,它才会在浏览器中呈现,但是在 app.get 中发布时,HTML 页面不会呈现(黑屏),但 HTML 代码是当我签入 Postman

时在响应正文中生成

下面是我的代码,

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

上面呈现了 required HTML 页面。

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

上面生成了 HTML 代码但没有在浏览器中呈现,我是不是遗漏了什么?

更新:

我使用生成HTML方法,但它似乎仍然以同样的方式工作,

app.use('/api-docs-html/BOOKING-CANCELLATION', function(req, res, next) {
    var pathArraySplit = req.originalUrl.split('/');
    var apiNameWithHyphen = pathArraySplit[2].trim()
    var apiNameWithUnderScore = apiNameWithHyphen.replace('-', '_');
    swaggerDocument = JSONConstructor.JSONConstructorTest(apiNameWithUnderScore)
    swaggerHtml = swaggerUi.generateHTML(swaggerDocument, swaggerUiOpts)
    next()
},swaggerUi.serveFiles(swaggerDocument, swaggerUiOpts))
app.get('/api-docs-html/BOOKING-CANCELLATION', (req, res) => { res.send(swaggerHtml) });

swaggerUi.serve是一个中间件函数所以需要和app.use(),Refer

一起使用

中间件 (app.use()) 和路由处理程序 (app.get()) 处理请求的功能不同,Refer

next() 中间件内部的调用会调用下一个中间件或路由处理程序,具体取决于接下来声明的那个。但是 next() 在路由处理程序中调用只会调用下一个路由处理程序。如果接下来有中间件,则跳过它。因此必须在所有路由处理程序之上声明中间件。

你可以这样使用,

app.use('/api-docs', swaggerUi.serve);
app.get('/api-docs', swaggerUi.setup(swaggerDocument));