如何在使用 swagger-ui-express 和 swagger-jsdoc 时正确使用 swagger 文件中的 $ref

Liz*_*lis 11 json ref node.js express swagger

我开始使用 swagger 和swagger-ui-expressswagger-jsdoc来自动记录我现有的 API,它是用nodejs和 express编写的(就像这里描述的一样 -示例)。

当我尝试在我的注释上添加一个$ref现有的JSON 模式文件(它与我的所有 js 文件位于我的项目中的同一目录中)时遇到了一个问题。

我的目录看起来像这样

我尝试编写本地路径 ( ./schema.json) 和绝对路径,尝试使用#,使用了许多语法,但没有任何效果。

我的注释是这样的:

/**
 * @swagger
 * /testing:
 *    get:
 *      description: This should show the json schema
 *      responses:
 *          200:
 *              description: "successful operation"
 *              schema:
 *                 $ref: "./schema.json"
 */
Run Code Online (Sandbox Code Playgroud)

我希望 swagger ui 在我的请求部分向我显示 JSON 模式。我收到以下错误 -

Resolver error at paths./testing.get.responses.200.schema.$ref
Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: './schema.json' basePath: 'undefined'.
Run Code Online (Sandbox Code Playgroud)

我在网上查了这个问题,找不到任何明确的答案。我看到了一个解决方案,建议我应该将我的架构放在服务器上并使用 URL 地址访问它,但我不想在这一点上这样做。

此外,在某些时候,我将方案保存在一个变量中,然后将其放入$ref并且它工作正常。唯一的问题是该方案在同一文件中包含了对某个元素的一些内部引用,而Swagger无法解析它们。

有没有办法$refswagger-ui-express 中正常工作?

小智 1

在这里遇到同样的问题并找到您的问题。

我刚刚解决了我的问题,所以我想我可能会有所帮助。

首先,你有没有尝试过:

schema:
      $ref: "schema.json"
Run Code Online (Sandbox Code Playgroud)

.就是他们在文档中教授的方式。