swagger-ui-express 不展示接口响应结果的问题解决
Chrome已获取包含预期数据的200响应,但Swagger未展示对应结果
当前Swagger配置
swaggerOptions = { openapi: '3.0.0', swaggerDefinition: { info: { title: 'Admin API', description: 'Admin API integration', version: "1.0", contact: { name: 'Vinicius A. Da Silva' }, servers: [ 'http://localhost:3000' ] }, produces: ["application/json"], securityDefinitions: { bearerAuth: { type: 'apiKey', name: 'Authorization', scheme: 'bearer', in: 'header', bearerFormat: 'JWT', }, }, security: [{ bearerAuth: [] }], }, apis: [__dirname + '/controller/*.js'] }
当前使用的JSDoc注释
/** * @swagger * /api/list?mdl={mdl}: * security: * - Bearer: [] * get: * description: Returns all users * responses: * '200': * description: Successfully returned paginated records * '403': * description: Not enough permissions read_modelName * parameters: * - name: mdl * in: query * description: Model name * required: true * schema: * type: string * format: string * responses: * '200': * description: Successfully inserted a user * content: * 'application/json': * schema: * type: object * description: test response * '403': * description: Not enough permissions */
异常表现
接口的响应UI区域无法正常展示内容,尽管Chrome Network面板已确认接口返回了携带预期数据的200状态响应。
问题根因
按照OpenAPI 3.0的结构规范,responses节点必须嵌套在具体HTTP方法定义(如get、post)的内部,不能放置在与HTTP方法平级的路径层级下。
原注释存在两处不符合规范的结构问题:
- 在get方法内部写了一组缺少content结构定义的responses
- 在路径层级(与get方法平级)重复写了另一组responses,导致Swagger解析时无法正确识别响应结构,无法正常渲染响应展示区域。
修正方案
移除路径层级下重复的responses配置,将所有响应规则统一嵌套在对应HTTP方法内部,修正后的JSDoc注释如下:
/** * @swagger * /api/list?mdl={mdl}: * security: * - Bearer: [] * get: * description: Returns all users * responses: * '200': * description: Successfully returned paginated records * '403': * description: Not enough permissions read_modelName * parameters: * - name: mdl * in: query * description: Model name * required: true * schema: * type: string * format: string */
内容的提问来源于stack exchange,提问作者viniciusalvess
相关产品推荐
相关产品推荐

