为何在ApiGateway中通过Swagger仅能查看最后一份API文档?
解决SwaggerUI仅显示最后一个API文档的问题
问题根源
你判断的完全正确——每次调用SwaggerUIBundle时都指定了同一个dom_id: '#swagger',新创建的Swagger实例会直接覆盖这个DOM元素内的所有旧内容,所以最终只会保留最后一个API的文档。
两种可行解决方法
方法1:为每个API生成独立DOM容器
修改renderUI函数,动态创建多个专属容器,让每个API的文档渲染到各自的容器中:
const renderUI = (specs?: Spec[]): void => { if (!specs) { return; } const rootContainer = document.getElementById('swagger'); if (!rootContainer) return; specs.forEach((spec, index) => { // 创建API标题区分不同文档 const apiTitle = document.createElement('h3'); apiTitle.textContent = spec.info.title || `API 实例 ${index + 1}`; rootContainer.appendChild(apiTitle); // 创建专属渲染容器 const apiContainer = document.createElement('div'); apiContainer.id = `swagger-container-${index}`; rootContainer.appendChild(apiContainer); // 渲染当前API到专属容器 SwaggerUIBundle({ spec: spec, dom_id: `#swagger-container-${index}`, deepLinking: true, openapi: '3.0.0', }); }); };
方法2:用SwaggerUI多文档切换功能(推荐)
SwaggerUI原生支持多文档切换,通过urls配置项传入所有API规范,会自动生成下拉菜单供用户切换,体验更统一:
const renderUI = (specs?: Spec[]): void => { if (!specs) { return; } // 转换为SwaggerUI要求的urls格式 const swaggerDocs = specs.map(spec => ({ name: spec.info.title || '未命名API', url: `data:application/json;base64,${btoa(JSON.stringify(spec))}` })); // 只初始化一次SwaggerUI,传入多文档配置 SwaggerUIBundle({ urls: swaggerDocs, dom_id: '#swagger', deepLinking: true, openapi: '3.0.0', defaultModelsExpandDepth: -1 // 可选:默认隐藏模型展开 }); };
额外优化:简化二进制转JSON逻辑
你getAPIGatewaySpec里的blobToJson可以用原生TextDecoder简化,不用手动循环拼接字符:
const blobToJson = (binArray: any) => { const decoder = new TextDecoder('utf-8'); return binArray.map((item: any) => JSON.parse(decoder.decode(item.body))); };
内容的提问来源于stack exchange,提问作者David D
相关产品推荐
相关产品推荐

