【问题标题】:swagger-ui-express is not rendering in browser but has response body in Postmaswagger-ui-express 不在浏览器中呈现,但在 Postman 中有响应正文
【发布时间】:2019-08-02 21:11:54
【问题描述】:

我正在尝试记录一个 API,为此我使用 swagger-ui-express。 当我使用以下内容时,

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

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

一切都很完美,但我希望 swaggerDoc 根据 URL 命中动态创建,因此我添加了以下代码。但是现在,HTML 页面永远不会在浏览器中呈现,但是当在 Postman 中点击时,它似乎具有与为前一种方法呈现 HTML 时相同的响应正文。

所以当我将上面的代码修改如下时,

    app.use('/api-docs/*', swaggerUi.serve)
    app.get('/api-docs/*', function(request, response, next){
        console.log(request.url);
        var apiNameSplitArray = request.url.split('/')
        var apiName = apiNameSplitArray[2]
        swaggerDoc = JSONConstructor.JSONConstructorTest(apiName.trim())
        next()
    })
    app.get('/api-docs/*', swaggerUi.setup(swaggerDoc))

它不起作用(不会在浏览器中呈现)。当我使用断点检查控制流时,我注意到以下方法执行顺序

  1. app.use
  2. 第二个app.get
  3. 第一个app.get

【问题讨论】:

    标签: node.js express swagger swagger-ui


    【解决方案1】:

    我也遇到了同样的问题,经过深入研究发现该问题与错误的响应标头有关。在我的例子中,响应头设置为res.setHeader('Content-Type', 'application/json');。删除后它起作用了。

    确保您的响应标头包含Content-Type: text/html; charset=utf-8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-30
      • 2021-04-03
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多