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

Swagger UI无法显示响应问题求助

问题

在ExpressJS应用中集成Swagger与Swagger UI后,执行任意请求时UI均无法显示响应。通过浏览器开发者工具确认服务器已返回正确JSON格式的响应,但Swagger UI未对其进行展示。请问遗漏了什么配置?

主应用文件app.js中的Swagger配置

const swaggerJSDoc    = require('swagger-jsdoc');
const swaggerUi       = require('swagger-ui-express');

/* SWAGGER ================================================================= */
const swaggerDefinition = {
  openapi: '3.0.0',
  info: {
    title: 'Express API',
    version: '1.0.0',
    description: "Bla bla",
    contact: {
      name: 'Website',
      url: 'https://www.somethingsomething.fi'
    }
  },
  servers: [
    {
      url: 'http://localhost:3000',
      description: 'Local development server'
    }
  ]
};

const options = {
  swaggerDefinition,
  // Paths to files containing OpenAPI definitions
  apis: ['./routes/api/v1/*.js'],
};

const swaggerSpec = swaggerJSDoc(options);

//add API doc route
app.use('/apidoc', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

接口文档注释示例

/**
 * @swagger
 * /v1/frameagreements:
 *  get:
 *    tags:
 *      - Frame Agreements
 *    summary: Retrieve a list of Frame Agreements.
 *    description: Retrieve a list of all Lease Objects. The sensitive information is removed from the results.
 */
 router.get("/", async (req, res, next) => {

...etc
解决方案

问题出在接口的Swagger注释中未定义响应(responses)的结构。Swagger UI需要明确知晓接口返回的数据格式,才能在请求完成后展示响应内容——哪怕服务器已经返回了正确的JSON,没有配置响应元数据的话,UI也不知道该如何解析和展示。

你需要在接口的Swagger注释中添加responses字段,指定对应HTTP状态码的响应结构,示例如下:

/**
 * @swagger
 * /v1/frameagreements:
 *  get:
 *    tags:
 *      - Frame Agreements
 *    summary: Retrieve a list of Frame Agreements.
 *    description: Retrieve a list of all Lease Objects. The sensitive information is removed from the results.
 *    responses:
 *      200:
 *        description: 成功获取框架协议列表
 *        content:
 *          application/json:
 *            schema:
 *              type: array
 *              items:
 *                type: object
 *                properties:
 *                  id:
 *                    type: string
 *                    description: 框架协议ID
 *                  name:
 *                    type: string
 *                    description: 框架协议名称
 *                  createdAt:
 *                    type: string
 *                    format: date-time
 *                    description: 创建时间
 */
 router.get("/", async (req, res, next) => {
  // 接口逻辑
});

补充说明:

  • 若不想手写重复的schema,可以先在components.schemas中定义复用结构,再在responses中引用
  • 至少要定义最常见的成功状态码(如200)的响应格式,Swagger UI才会正确渲染响应内容
  • 确保content中的application/json与接口实际返回的Content-Type一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:37:42