当从Swagger编辑器发出请求时,如何避免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编辑器发出请求时,出现错误:
But when I make a request from Swagger Editor, I get an error:
找不到错误服务器或发生错误
ERROR Server not found or an error occurred
我在做什么错了?
推荐答案
所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:8081 .
这是一个 CORS 问题. https://now.httpbin.org 上的服务器不支持CORS,因此浏览器不会允许网页从其他域提供服务以通过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 的所有者"https://enable-cors.org/server.html" rel ="nofollow noreferrer">支持CORS .
Ask the owners of https://now.httpbin.org to support 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.
如果您是所有者,请考虑将Swagger UI托管在同一服务器和端口(现在为httpbin.org:443)上,以完全避免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.
- Bypass CORS in Chrome
- Bypass CORS in Firefox
使用 SwaggerHub 而不是Swagger编辑器来编辑和测试您的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编辑器发出请求时,如何避免CORS错误(“无法提取"或“未找到服务器或发生错误")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!