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

swagger-jsdoc配置200响应示例未在Swagger UI显示求助

swagger-jsdoc响应示例在Swagger UI不显示的问题解决

可能的原因及修复方法

1. 调整示例定义层级

你当前在每个schema属性上单独添加example,但Swagger UI对这种分散的示例渲染可能存在兼容问题。可以改为在content/application/json层级直接定义完整的响应示例,这种方式的渲染优先级更高,也更稳定:

修改后的配置代码:

/**
* @swagger
* /api/v1/admin-users:
*   get:
*     summary: 获取所有管理员用户
*     description: 获取所有管理员用户列表
*     tags: [管理员用户]
*     security:
*       - Bearer: []
*     responses:
*       200:
*         description: 请求成功
*         content:
*           application/json:
*             schema:
*               type: object
*               properties:
*                 totalRecords:
*                   type: integer
*                 currentPage:
*                   type: integer
*                 totalPages:
*                   type: integer
*                 result:
*                   type: array
*                   items:
*                     type: object
*                     properties:
*                       id:
*                         type: string
*                       username:
*                         type: string
*                       email:
*                         type: string
*             # 在这里定义完整的响应示例
*             example:
*               totalRecords: 1
*               currentPage: 1
*               totalPages: 10
*               result:
*                 - id: "605c72efb87c4e2e2d3b1b70"
*                   username: "admin_user"
*                   email: "admin@example.com"
*       401:
*         description: 未授权
*       404:
*         description: 资源不存在
*       500:
*         description: 服务器内部错误
*/

2. 明确指定OpenAPI版本

swagger-jsdoc v6.x默认生成OpenAPI 3.0规范,但如果初始化时未明确指定,可能会导致解析异常。检查你的swagger-jsdoc初始化代码,确保设置了正确的openapi版本:

const swaggerJsdoc = require('swagger-jsdoc');

const swaggerOptions = {
  definition: {
    openapi: '3.0.0', // 必须明确指定版本
    info: {
      title: '你的API文档标题',
      version: '1.0.0',
    },
  },
  apis: ['./src/routes/**/*.js'], // 替换为你的路由文件路径
};

const swaggerSpec = swaggerJsdoc(swaggerOptions);

3. 清除缓存

Swagger UI会缓存旧的文档内容,修改配置后,先重启服务器,再用快捷键强制刷新浏览器(Ctrl+Shift+R),确保新配置生效。

同类问题情况

不少使用swagger-jsdoc v6.x + swagger-ui-express v5.x的开发者都遇到过这个问题,大多是因为示例定义层级不对,或者OpenAPI版本未明确导致的渲染异常,调整上述配置后基本都能解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:38:13