You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js环境下如何下载Swagger UI对应的API文档JSON文件?

实现Swagger UI的API文档JSON下载功能

方法一:利用Swagger UI默认下载按钮(推荐)

这种方式无需自定义UI,让Swagger UI从URL加载文档后,默认就会显示下载按钮:

  1. 新增路由返回API文档的JSON数据:
// 暴露API文档的JSON接口
app.get('/api-docs/spec', (req, res) => {
  res.json(require('./docs'));
});
  1. 修改Swagger UI配置,指定从上述URL加载文档:
// 替换原有的swaggerUI.setup配置
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(undefined, {
  swaggerOptions: {
    url: '/api-docs/spec' // 指定文档的JSON地址
  }
}));

启动服务后访问/api-docs,Swagger UI顶部会自动出现下载按钮,点击即可下载JSON格式的API文档。


方法二:自定义下载按钮(适合保持直接传入docs对象的场景)

如果不想改变现有文档加载方式,仍直接传入docs对象,可以通过自定义UI添加下载按钮:

  1. 新增下载路由:
// 提供文档下载的接口
app.get('/api-docs/download', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Content-Disposition', 'attachment; filename="node-service-api-docs.json"');
  res.send(require('./docs'));
});
  1. 修改Swagger UI的setup配置,插入自定义下载按钮:
// 自定义包含下载按钮的HTML模板
const customHtml = `
<div class="swagger-ui">
  <div class="topbar">
    <div class="download-url-wrapper">
      <a href="/api-docs/download" class="download-url-button" download>下载API文档JSON</a>
    </div>
  </div>
  <div id="swagger-ui"></div>
</div>
`;

// 应用自定义配置
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(docs, {
  customHtml
}));

访问/api-docs时,顶部会显示自定义的下载按钮,点击即可触发下载。


额外修正:你的docs.js结构问题

当前docs.js中servers、components等字段嵌套在info里,这不符合OpenAPI规范,修正后的正确结构如下:

{
  "openapi": "3.0.1",
  "info": {
    "version": "1.0.0",
    "title": "NODE SERVICE",
    "description": "This is a API docs",
    "contact": {
      "name": "Developer",
      "email": "developer@google.com",
      "url": "https://mkibui.me"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
    }
  },
  "servers": [
    {
      "url": "http://localhost:9090/api",
      "description": "Local server"
    }
  ],
  "components": {},
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "paths": {}
}

修正后Swagger UI才能正确解析文档结构。

内容的提问来源于stack exchange,提问作者Shanthi B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:17:44