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

NodeJS中如何在Swagger UI注释代码里引用外部变量?

解决Swagger-JSDoc中无法引用外部变量作为Example的问题

问题原因

swagger-jsdoc是静态解析JSDoc注释的,它不会执行注释里的JavaScript代码或变量引用。你在注释里写的任何变量名,都会被直接当作字符串字面量处理,所以不管用哪种写法,Swagger UI都会把它显示成字符串,而不是变量对应的实际值。

可行解决方案

直接在生成Swagger文档后,动态修改Schema的Example值,步骤如下:

  1. 先保留基础的Swagger注释,把raw_data的example留空或者写个占位符:
//! Schema POST
/**
 * @swagger
 * components:
 *   schemas:
 *      Phonation:
 *       type: object
 *       required:
 *         - date
 *         - status
 *         - raw_data
 *       properties:
 *         date:
 *           type: string
 *           timestamp-format: yy-MM-dd HH:mm:ss
 *           example: "2022-09-21 14:56:15"
 *         status:
 *           type: integer
 *           example: 3
 *         raw_data:
 *           type: string
 *           format: binary
 *           example: "" # 留空占位
 */
  1. 在生成Swagger Spec的代码中,手动注入变量值:
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const fs = require("fs");
const express = require('express');
const app = express();

// 读取并解析外部JSON数据
const phonationRaw_data = fs.readFileSync("payloads/phonationData.json");
const phonationParsedData = JSON.parse(phonationRaw_data);

// Swagger-JSDoc基础配置
const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: '你的API文档',
      version: '1.0.0',
    },
  },
  apis: ['./path/to/your/routes.js'], // 替换成你的路由文件路径
};

// 生成初始Swagger文档
let swaggerSpec = swaggerJsdoc(swaggerOptions);

// 动态修改Phonation Schema的raw_data示例值
swaggerSpec.components.schemas.Phonation.properties.raw_data.example = phonationParsedData.raw_data;

// 挂载Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// 启动服务
app.listen(3000, () => console.log('Server running on port 3000'));

补充说明

  • 如果你有多个需要动态注入的示例值,可以用循环遍历的方式批量修改Schema,避免重复代码。
  • 确保phonationParsedData.raw_data的类型和Schema中定义的raw_data类型一致(这里是string),否则Swagger UI可能会显示异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:15:46