如何向 Swagger UI 的响应添加 CORS 标头

问题描述 投票:0回答:1

当我在本地通过 Swagger UI 文档调用以下 AWS API 网关 URL 时,我无法在 Swagger UI 中获取消息。 CORS 已在服务器上启用,但仅在 Swagger UI 上出错。相同的 Curl req 在本地执行良好。

Swagger UI error

以下是我在开发者工具中看到的消息。我对 Swagger 很陌生,想知道如何在响应标头中设置 CORS。

从源“http://localhost:8080”获取“https://example.com/GetEmployees”的访问已被 CORS 策略阻止:请求中不存在“Access-Control-Allow-Origin”标头资源。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

openapi: 3.0.1
info:
  title: API's
  description: >-
    REST API's for abc
  contact:
    name: ABC
    email: ABC
  version: "1.0.0"
servers:
  - url: "http://localhost:8080/"
tags:
  - name: Employees     
    description: Get Employees info 
paths:
  /Employees:
    get:
      description: Get Employee info 
      summary: Get Employee.
      tags:
      - Employees
      security:
      - basicAuth:
        - '[]'
      operationId: GetEmployees
      parameters:
      - name: EmpNbr
        in: query
        description: Employee ID(Example:0123456789)
        required: true
        schema:
          type: string
      - name: DateofJoin
        in: query
        description: Input DateofJoin(Example:mmddyyyy(01012023))
        required: true
        schema:
          type: string
      responses:
        '200':
          description: OK.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Employees'
components:
  schemas:
    Employeewithroot:
      properties:
        Employee:
          items:
            $ref: '#/components/schemas/Employees'
          type: array
          x-go-name: Employees
    Employees:
      properties:
        EmpNbr:
          $ref: '#/components/schemas/NullString'
        DateofJoin:
          $ref: '#/components/schemas/NullString'
        DeptId:
          $ref: '#/components/schemas/NullString'
        DeptName:
          $ref: '#/components/schemas/NullString'
        x-go-package: pkg/model
  securitySchemes:
    basicAuth:
      type: apiKey
      name: Authorization
      in: header 

添加了问题的步骤。

尝试添加如下标头,但

swagger.yaml
变得无效。

      responses:
        '200':
          description: OK.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/VisitLimitHdr'
                headers:
                  Access-Control-Allow-Origin:
                    type: 'string'  
aws-api-gateway openapi swagger-ui
1个回答
0
投票

headers
content

的兄弟姐妹
responses:
        '200':
          description: OK.
          headers:
            Access-Control-Allow-Origin:
              type: 'string'  
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/VisitLimitHdr'
                

在 OpenAPI 中设置它不会执行任何操作,这只是描述如何返回响应。需要在服务器上启用 CORS

© www.soinside.com 2019 - 2024. All rights reserved.