在无服务器的 express 应用程序中使用 swagger 多次重定向到 swagger 端点

Multiple redirects to the swagger endpoint using swagger in express app with serverless

我正在使用 express-serverless 制作应用程序,我想在离线开发期间使用 swagger-jsdoc 和 swagger-ui-express。 这是我的 swagger 配置:

const express = require('serverless-express/express');
const router = express.Router();

const options = {
    swaggerDefinition: {
        info: {
            title: 'REST - Swagger',
            version: '1.0.0',
            description: 'REST API with Swagger doc',
            contact: {
                email: 'me@someemail.com'
            }
        },
        tags: [
            {
                name: 'Stuff',
                description: 'Stuff API'
            }
        ],
        schemes: ['http'],
        host: 'localhost:9002',
        basePath: '/docs'
    },
    apis: ['./**/route.js']
}

const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = swaggerJSDoc(options);
require('swagger-model-validator')(swaggerSpec);

router.get('/api-docs.json', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(swaggerSpec);
})

router.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

function validateModel(name, model) {
    const responseValidation = swaggerSpec.validateModel(name, model, false, true)
    if (!responseValidation.valid) {

        console.error(responseValidation.errors);
        throw new Error(`Some error`)
    }
}

module.exports = {
    router,
    validateModel
}

并且在 handler.js 文件中:

// ... some imports and code
app.use("/", index);
// ... others routes

// Swagger
app.use("/docs", swagger.router); // <-- it refers to the configuration above 

exports.handler = handler(app);

当我访问 http://localhost:9002/docs/api-docs.json I get the configuration JSON but if I access http://localhost:9002/docs/api-docs 时,我得到多次重定向到同一个 url,并且从不显示 Swagger 界面。

更新

对不起我的错误,我使用 serverless-express/express 而不是 express

如有任何帮助,我们将不胜感激。 提前致谢!

我找到了这个替代解决方案:

  1. 我在 https://github.com/swagger-api/swagger-ui

  2. 下载 swagger-ui
  3. 将 dist 文件夹复制到我在 Express 应用程序中的 public 文件夹

  4. 将文件夹名称 "dist" 更改为 "api-docs"

  5. 并在 index.html 内的 "api-docs" 文件夹中更改行

    url = "http://petstore.swagger.io/v2/swagger.json";

至:

url: "http://localhost:9002/api-docs.json",

现在当我访问http://localhost:9002/api-docs/index.html 我可以看到 swagger-ui 页面工作正常!