Can't setup swagger - Cannot read property 'parameters' of undefined

陌路散爱 提交于 2020-12-13 04:12:33

问题


I am having a problem with setting up the swagger into my node.js application. I am using swagger-jsdoc and swagger-ui-express for creating documentation. Here are the versions

"swagger-jsdoc": "3.5.0", "swagger-ui-express": "4.1.3"

Below is the configs, which I pass to swagger-jsdoc.

openapi: 3.0.0
info:
  description: test
  version: 3.0.0
  title: U-CRM api documentation
  termsOfService: http://swagger.io/terms/
servers:
  - url: 'https://localhost:5000'
    description: Local server
tags:
- name: U-CRM
  description: CRM for university
components:
  parameters:
    $ref: 'components/parameters/index.yml'
  schemas:
    $ref: 'components/schemas/index.yml'
paths:
  $ref: '#/paths/index.yml'

After all, I get an error

Cannot read property 'parameters' of undefined

Actually, it is surprising to me, as I read swagger docs carefully. What could be the problem?


回答1:


OpenAPI does not support $ref everywhere. $ref can only be used in specific places where the OpenAPI Specification explicitly states that the value of a field can be a "Reference Object".

For example, $ref is not allowed directly under paths, under components/parameters and components/schemas - you can only reference individual paths, parameters and schemas.

The correct version of your example is:

paths:
  /foo:
    $ref: '#/paths/index.yml#/~1foo'  # $ref to root node `/foo` in `paths/index.yml`
  /bar:
    $ref: '#/paths/index.yml#/~1bar'  # $ref to root node `/bar` in `paths/index.yml`

components:
  parameters:
    param1:
      $ref: 'components/parameters/index.yml#/param1'
    param2:
      $ref: 'components/parameters/index.yml#/param2'
  schemas:
    schema1:
      $ref: 'components/schemas/index.yml#/schema1'
    schema2:
      $ref: 'components/schemas/index.yml#/schema2'


If you want to use $ref in random places, you'll have to pre-process your definition using a parser/tool that can resolve arbitrary $refs; this will give you a valid OpenAPI file that can be used with OpenAPI-compliant tools. One such pre-processing tool is json-refs, you can find an example of pre-processing here.



来源:https://stackoverflow.com/questions/60271342/cant-setup-swagger-cannot-read-property-parameters-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!