我无法弄清楚我的API网关或swagger-ui-express的正确设置。lambda函数成功运行并返回html,但是相关资源无法加载并得到404错误。
const app = express();
const swaggerUI = require('swagger-ui-express');
const serverlessExpress = require('@vendia/serverless-express');
const Stage = process.env.Stage;
const apiId = process.env.apiId;
const options = {
customCss: '.swagger-ui .topbar { display: none }',
customCss: '.swagger-ui .topbar { background-color: red }'
}
let serverlessExpressInstance
async function asyncTask() {
// load latest spec from API Gateway export removed to simplicity reasons.
const swaggerDocument = spec;
console.log("load swagger file complete.");
return swaggerDocument
}
async function setup(event, context) {
const swaggerDocument = await asyncTask()
console.log(swaggerDocument)
app.use('/api-doc', swaggerUI.serveWithOptions({ redirect: false }));
app.use('/api-doc', swaggerUI.setup(swaggerDocument, options));
console.log("setup of swagger complete");
serverlessExpressInstance = serverlessExpress({ app })
return serverlessExpressInstance(event, context)
}
function handler(event, context) {
if (serverlessExpressInstance) return serverlessExpressInstance(event, context)
return setup(event, context)
}
exports.handler = handler在API网关上设置如下:

这两个资源都指向lambda函数。当我通过:https://.execute-api..amazonaws.com/dev/api-doc加载页面时,会引发以下错误:

如何确保通过正确的路径正确地加载资源.dev/api/doc/.
发布于 2022-09-22 14:14:59
您可能会收到这些错误,因为swagger配置为查找图像/js资源,而且express不提供这些文件。您可能会使用类似于serverless-http的这,但我不太确定是否可以尝试将表达式强制应用到API网关lambda函数的响应中。
作为另一种选择,我成功地在API Gateway lambda函数上启动并运行了swagger,直接获取了swagger JSON。
import { APIGateway } from "aws-sdk";
import { env } from "../../helpers/env";
const API_ID = env("API_ID", "");
export const handler = async () => {
const apiGateway = new APIGateway({
apiVersion: "2018-11-29",
});
const apiGatewayExport = await apiGateway
.getExport({
exportType: "swagger",
restApiId: API_ID,
stageName: "prod",
accepts: "application/json",
parameters: {
extensions: "apigateway",
},
})
.promise();
if (!apiGatewayExport.body) {
throw new Error("No body found in API Gateway Export");
}
return {
statusCode: 200,
headers: {
"Content-Type": "text/html",
},
body: generateSwaggerPageBody(apiGatewayExport.body?.toString()),
};
};
const generateSwaggerPageBody = (swaggerSpec: string) => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css">
</head>
<body>
<div id="swagger"></div>
<script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
dom_id: '#swagger',
spec: ${swaggerSpec}
});
</script>
</body>
</html>`;我通过SDK直接从API获取API信息,然后直接返回一个带有标签的html页面,直接加载swagger --不需要任何快速开销。
https://stackoverflow.com/questions/69232672
复制相似问题