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

2023-12-08

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

访问从原点 '' 获取 'http://本地主机:8080' 已被 CORS 政策阻止:回应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

这是我调用 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,根据您的请求,我注意到您有一个自定义标头: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>

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

由于 CORS 问题,无法从 Azure APIM 后面的网页调用 API 的相关文章

随机推荐