azure - 由于 CORS 问题,无法从 Azure APIM 后面的网页调用 API

标签 azure cors

我正在使用 Azure APIM,我的 API 托管在由 .net core 编码的 Azure 应用服务上。我已经在 APIM 后面配置了我的 api。然而,当我尝试调用我的 API 时,我遇到了这个问题:

Access to fetch at '' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是我调用 API 的 js 代码:

var url='<the url of my api in APIM>';
fetch(url, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Seckey":"xxxxxx"
    },
    body: '<some json content>'
    }).then(function(res) {
        console.log("Response succeeded?", JSON.stringify(res.status));
        console.log(JSON.stringify(res));
    }).catch(function(e) {
    console.log("fetch fail", JSON.stringify(e));
});

我知道这是一个 CORS 问题,并且我已根据此文档在 APIM 中配置了 CORS 策略: https://learn.microsoft.com/en-us/azure/api-management/api-management-cross-domain-policies#CORS

但是并没有解决这个问题。那么我错过了什么吗?

提前致谢。

最佳答案

正如 @Thiago Custodio 所说,您应该在 Azure 应用服务和 APIM 中配置 CROS。

顺便说一句,如果您为 Azure 应用服务启用了 CROS,请检查您是否在 APIM 中正确配置了 CORS,根据您的请求,我注意到您有一个自定义 header :Seckey,您是否在 CORS 策略中配置了它?

如果没有,请尝试下面的 CORS 策略,否则您将遇到 CORS 问题:

<cors >
    <allowed-origins>
        <origin>http://localhost:8080/</origin> 
    </allowed-origins>
    <allowed-methods preflight-result-max-age="300">
        <method>POST</method>
    </allowed-methods>
    <allowed-headers>
        <header>Content-Type</header>
        <header>Seckey</header>
    </allowed-headers>
</cors>

希望有帮助。

关于azure - 由于 CORS 问题,无法从 Azure APIM 后面的网页调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334156/

相关文章:

Spring Boot 应用程序将从 Key Vault 读取配置并连接到 SQL?

Azure API 管理 - 客户端证书身份验证责任?

azure - 逻辑应用标准工作流触发器失败

spring-boot - Netflix Zuul CORS

asp.net-mvc - MVC Web API Angular App ('http://localhost:4200' 已被 CORS 策略阻止)

azure - 访问 PowerApps 的源代码并将其托管在其他地方

c# - 有没有直接的方法将容器日志从物联网边缘设备发送到azure日志分析工作区?

java - 如何在JAVA中创建自己的代理服务器来解决CORS问题?

javascript - 在浏览器中下载视频而不是在新标签页中播放 [CORS]

asp.net-mvc - JSON 与 JSONP 与 CORS