首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用API网关建立swagger-ui-express

利用API网关建立swagger-ui-express
EN

Stack Overflow用户
提问于 2021-09-18 07:47:57
回答 1查看 478关注 0票数 0

我无法弄清楚我的API网关或swagger-ui-express的正确设置。lambda函数成功运行并返回html,但是相关资源无法加载并得到404错误。

代码语言:javascript
复制
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/.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-22 14:14:59

您可能会收到这些错误,因为swagger配置为查找图像/js资源,而且express不提供这些文件。您可能会使用类似于serverless-http,但我不太确定是否可以尝试将表达式强制应用到API网关lambda函数的响应中。

作为另一种选择,我成功地在API Gateway lambda函数上启动并运行了swagger,直接获取了swagger JSON。

代码语言:javascript
复制
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 --不需要任何快速开销。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69232672

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档