从 Swagger Editor 发出请求时,如何避免 CORS 错误(“无法获取"或“未找到服务器或发生错误")? [英] How to avoid CORS errors ("Failed to fetch" or "Server not found or an error occurred") when making requests from Swagger Editor?
问题描述
我有以下 OpenAPI 定义:
I have the following OpenAPI definition:
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
我想从 响应中检索 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 发出请求时,我得到一个错误:
But when I make a request from Swagger Editor, I get an error:
ERROR 服务器未找到或发生错误
ERROR Server not found or an error occurred
我做错了什么?
推荐答案
请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://localhost:8081' 因此不允许访问.
这是一个CORS 问题.https://now.httpbin.org 的服务器不支持 CORS,因此浏览器不会让 web从其他域提供的页面以通过 JavaScript 向 now.httpbin.org 发出请求.
This is a CORS issue. The server at https://now.httpbin.org does not support CORS, so the browsers won't let web pages served from other domains to make requests to now.httpbin.org from JavaScript.
你有几个选择:
向 https://now.httpbin.org 的所有者询问 支持 CORS.
注意:服务器不得要求对预检 OPTIONS
请求进行身份验证.OPTIONS
请求应返回 200 并带有正确的 CORS 标头.
Note: The server must not require authentication for preflight OPTIONS
requests. OPTIONS
requests should return 200 with the proper CORS headers.
如果您是所有者 - 考虑在同一服务器和端口(now.httpbin.org:443)上托管 Swagger UI,以完全避免 CORS.
If you are the owner - consider hosting Swagger UI on the same server and port (now.httpbin.org:443) to avoid CORS altogether.
在您的浏览器中禁用 CORS 限制.这会降低浏览器的安全性,因此只有在您了解风险的情况下才这样做.
Disable CORS restrictions in your browser. This reduces browser security so only do this if you understand the risks.
使用 SwaggerHub 而不是 Swagger Editor 来编辑和测试您的 API 定义.SwaggerHub 代理通过其服务器试用"请求,因此它不受 CORS 限制.(披露:我为制作 SwaggerHub 的公司工作.)
Use SwaggerHub instead of Swagger Editor to edit and test your API definitions. SwaggerHub proxies "try it out" requests through its servers so it's not subject to CORS restrictions. (Disclosure: I work for the company that makes SwaggerHub.)
顺便说一句,您的响应定义无效.响应缺少 description
并且 schema
错误(例如,有一个额外的 items
关键字).应该是:
By the way, your response definition is not valid. The response is missing a description
and the schema
is wrong (e.g. has an extra items
keyword). It should be:
responses:
200:
description: OK
schema:
type: object
properties:
now:
type: object
properties:
rfc2822:
type: string
这篇关于从 Swagger Editor 发出请求时,如何避免 CORS 错误(“无法获取"或“未找到服务器或发生错误")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!