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

与世无争的帅哥 提交于 2021-01-28 06:10:54

问题


I'm making an application with express-serverless and I want to use swagger-jsdoc and swagger-ui-express during offline development. This is my configuration for 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
}

And in handler.js file:

// ... 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);

When I access http://localhost:9002/docs/api-docs.json I get the configuration JSON but if I access http://localhost:9002/docs/api-docs I get multiple redirections to this same url and never shows the Swagger interface.

UPDATE

Sorry my mistake, i am using serverless-express/express instead express

Any help would be appreciated. Thanks in advance!


回答1:


I find this alternative solution:

  1. I download the swagger-ui at https://github.com/swagger-api/swagger-ui

  2. Copy the dist folder to my public folder in the express app

  3. Change folder name "dist" to "api-docs"

  4. And inside index.html in the "api-docs" folder change the line

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

to:

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

Now when i access to http://localhost:9002/api-docs/index.html I can see the swagger-ui page working ok !



来源:https://stackoverflow.com/questions/55174859/multiple-redirects-to-the-swagger-endpoint-using-swagger-in-express-app-with-ser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!