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

Swagger不显示接口端点:Node.js API文档提示No operations defined in spec

问题原因

  • 你混用了两种Swagger配置逻辑:既准备了完整的JSON配置文件,又用swagger-jsdoc生成配置,两者逻辑冲突
  • swagger-jsdoc的apis配置是用来扫描文件中的JSDoc注释生成接口定义的,不会直接读取你写好的完整JSON结构,所以生成的配置里没有paths字段,才会出现无接口的提示
  • 配置规范不兼容:你的JSON文件用的是Swagger 2.0规范,但swagger-jsdoc的swaggerDefinition里用了OpenAPI 3.x才有的servers字段,进一步导致配置解析异常

解决方法(二选一即可)

方案一:直接使用现成的JSON配置(最推荐,改动最小)

你已经写好了完整的接口定义,完全不需要用swagger-jsdoc生成,直接修改app.js代码即可:

// 删掉swagger-jsdoc相关的引用和代码
const swaggerUI = require('swagger-ui-express')
const apiDoc = require('./swagger-doc/api-doc.json')

// 直接传入你写好的配置初始化Swagger页面
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(apiDoc))

改完重启服务就能看到接口了,不需要其他调整,还可以卸载不需要的swagger-jsdoc依赖。


方案二:保留swagger-jsdoc的使用

如果后续需要用JSDoc注释生成接口,需要统一配置规范,把已有JSON的内容合并到swaggerDefinition中:

const swaggerJsonDoc = require('swagger-jsdoc')
const swaggerUI = require('swagger-ui-express')
const apiDoc = require('./swagger-doc/api-doc.json')

const swaggerOptions = {
    swaggerDefinition: {
        // 明确指定使用Swagger 2.0规范
        swagger: "2.0",
        info: {
            title: "API's Document",
            version: "1.0.0.1",
            description: "This document will walk you through all the API end points in swagger",
        },
        // 从已有JSON中读取基础配置
        host: apiDoc.host,
        basePath: apiDoc.basePath,
        schemes: apiDoc.schemes,
        consumes: apiDoc.consumes,
        produces: apiDoc.produces,
        // 直接引入已写好的接口、模型、标签配置
        paths: apiDoc.paths,
        definitions: apiDoc.definitions,
        tags: apiDoc.tags
    },
    // 如果有其他带Swagger注释的接口文件,可把路径填到这里,否则留空即可
    apis: []
}

const swaggerDocs = swaggerJsonDoc(swaggerOptions)
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 10:27:02