问题看似简单,但即使过了几个小时也无法解决。 每次我创建 APIM 实例并在全局级别的入站策略中启用 CORS 策略时,我在测试任何 API 时都会收到以下错误消息。
开发者门户中的错误消息:
Since the browser initiates the request, it requires Cross-Origin Resource Sharing (CORS) enabled on the server
我通过导航到门户开发人员 --> 门户概述 --> 启用 CORS(单击按钮) --> 手动应用来启用 CORS 策略。
<cors allow-credentials="true">
<allowed-origins>
<origin>https://dev-apimdemo-apim.developer.azure-api.net</origin>
<origin>https://dev-apimdemo-apim.azure-api.net</origin>
</allowed-origins>
<allowed-methods preflight-result-max-age="300">
<method>*</method>
</allowed-methods>
<allowed-headers>
<header>*</header>
</allowed-headers>
<expose-headers>
<header>*</header>
</expose-headers>
</cors>
我从未添加任何自定义策略或任何内容,只是启用了 CORS。 我还缺少什么?
我尝试在我的环境中重现相同的内容,如下所示:
我创建了一个 Azure APIM 并在门户概述中启用了
CORS
:
请检查您是否已在全局级别添加CORS政策,如下所示:
转到 API -> 所有 API -> 入站处理 -> 添加策略 -> CORS
<policies>
<inbound>
<cors allow-credentials="true">
<allowed-origins>
<origin>https://testapim3394.developer.azure-api.net</origin>
</allowed-origins>
<allowed-methods preflight-result-max-age="300">
<method>*</method>
</allowed-methods>
<allowed-headers>
<header>*</header>
</allowed-headers>
<expose-headers>
<header>*</header>
</expose-headers>
</cors>
</inbound>
<backend>
<forward-request/>
</backend>
<outbound/>
<on-error/>
</policies>
CORS 策略将添加到入站处理中,如下所示:
我能够登录开发者门户,如下所示:
当我尝试执行该操作时,我能够成功执行,没有任何 CORS 错误:
确保您传递有效的订阅密钥标头。
如果问题仍然存在,请尝试使用以下 CORS 策略,方法包括:
<cors>
<allowed-origins>
<origin>*</origin>
</allowed-origins>
<allowed-methods>
<method>GET</method>
<method>POST</method>
<method>PUT</method>
<method>DELETE</method>
<method>HEAD</method>
</allowed-methods>
<allowed-headers>
<header>*</header>
</allowed-headers>
<expose-headers>
<header>*</header>
</expose-headers>
</cors>
或者尝试用
<origin>https://*.azure-api.net/</origin>
替换 origin
参考:
我们在全局级别启用了 CORS 策略,但有些东西仍然不正确,我们收到相同的“CORS”错误,我们在策略方面尝试了所有方法,使用“base”和“CORS”策略,手动更改它,但问题仍然存在。
有趣的是,有些 API 可以工作,有些则不能。 Postman 工作正常,但开发者门户返回相同的错误“由于浏览器发起请求,因此需要在服务器上启用跨域资源共享 (CORS)”。这很奇怪。也许有人有任何想法,可能出了什么问题?