问题
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:
I download the swagger-ui at https://github.com/swagger-api/swagger-ui
Copy the dist folder to my public folder in the express app
Change folder name "dist" to "api-docs"
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