使用无服务器快速应用程序中的 swagger 多次重定向到 swagger 端点 [英] Multiple redirects to the swagger endpoint using swagger in express app with serverless
问题描述
我正在使用 express-serverless 制作一个应用程序,我想在离线开发期间使用 swagger-jsdoc 和 swagger-ui-express.这是我对 swagger 的配置:
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
}
在 handler.js 文件中:
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);
当我访问 http://localhost:9002/docs/api-docs.json 我得到了配置 JSON 但如果我访问 http://localhost:9002/docs/api-文档 我多次重定向到同一个网址,但从未显示 Swagger 界面.
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.
更新
抱歉我的错误,我使用 serverless-express/express 代替 express
任何帮助将不胜感激.提前致谢!
Any help would be appreciated. Thanks in advance!
推荐答案
我找到了这个替代解决方案:
I find this alternative solution:
将 dist 文件夹复制到我在 express 应用中的公共文件夹
Copy the dist folder to my public folder in the express app
将文件夹名称dist"更改为api-docs"
Change folder name "dist" to "api-docs"
在api-docs"文件夹中的 index.html 中更改行
And inside index.html in the "api-docs" folder change the line
url = "http://petstore.swagger.io/v2/swagger.json";
到:
url: "http://localhost:9002/api-docs.json",
现在当我访问 http://localhost:9002/api-docs/index.html 时.html我可以看到 swagger-ui 页面工作正常!
Now when i access to http://localhost:9002/api-docs/index.html I can see the swagger-ui page working ok !
这篇关于使用无服务器快速应用程序中的 swagger 多次重定向到 swagger 端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!