从 Swagger Editor 发出请求时如何避免 CORS 错误("Failed to fetch" 或 "Server not found or an error occurred")?

How to avoid CORS errors ("Failed to fetch" or "Server not found or an error occurred") when making requests from Swagger Editor?

我有以下 OpenAPI 定义:

swagger: "2.0"

info:
  version: 1.0.0
  title: Simple API
  description: A simple API to learn how to write OpenAPI Specification

schemes:
  - https
host: now.httpbin.org
paths:
  /:
    get:
      summary: Get date in rfc2822 format
      responses:
        200:
          schema:
            type: object
            items:
              properties:
                now:
                  type: object
                    rfc2822:
                      type: string

我想从 response:

中检索 rfc2822
{"now": {"epoch": 1531932335.0632613, "slang_date": "today", "slang_time": "now", "iso8601": "2018-07-18T16:45:35.063261Z", "rfc2822": "Wed, 18 Jul 2018 16:45:35 GMT", "rfc3339": "2018-07-18T16:45:35.06Z"}, "urls": ["/", "/docs", "/when/:human-timestamp", "/parse/:machine-timestamp"]}  

但是当我从 Swagger Editor 发出请求时,出现错误:

ERROR Server not found or an error occurred

我做错了什么?

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

这是一个 CORS issue. The server at https://now.httpbin.org 不支持 CORS,因此浏览器不会让来自其他域的网页从 JavaScript 向 now.httpbin.org 发出请求。

您有几个选择:

  • 询问 https://now.httpbin.org to support CORS.

    的所有者

    注意: 服务器不得要求对预检 OPTIONS 请求进行身份验证。 OPTIONS 请求应该 return 200 具有适当的 CORS headers.

  • 如果您是所有者 - 考虑在同一服务器和端口 (now.httpbin.org:443) 上托管 Swagger UI 以完全避免 CORS。

  • 在浏览器中禁用 CORS 限制。 这会降低浏览器的安全性,因此只有在您了解风险的情况下才这样做。

  • 使用 SwaggerHub 而不是 Swagger Editor 来编辑和测试您的 API 定义。 SwaggerHub 通过其服务器代理 "try it out" 请求,因此它不受 CORS 限制。 (披露:我在制作 SwaggerHub 的公司工作。)


顺便说一下,您的响应定义无效。响应缺少 description 并且 schema 是错误的(例如,有一个额外的 items 关键字)。应该是:

      responses:
        200:
          description: OK
          schema:
            type: object
            properties:
              now:
                type: object
                properties:
                  rfc2822:
                    type: string