【发布时间】:2018-06-25 23:20:31
【问题描述】:
对 APP 服务的任何 Ajax / JQuery 调用(http://xxxx.azurewebsites.net)都会抛出以下错误
跨域请求被阻止:同源策略不允许读取 远程资源在 http://api-xxx.azurewebsites.net/api/demo/1234567。 (原因:CORS 标头 ‘Access-Control-Allow-Origin’ 不匹配 ‘(null)’)。
注意事项:
1. CORS 在 Azure 门户中设置为 *
2. REST API 也 CORS 已启用。
config.EnableCors();
控制器级别的CORS设置
[EnableCors(origins: "*", headers: "*", methods: "*")]
REST API Web.Config 设置
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
jQuery 脚本
<script type="text/javascript">
$(document).ready(function () {
$("#b1").click(function () {
var jsondata = $('#s1').text();
$.ajax({
url: "http://api-xxx.azurewebsites.net/api/demo/1234567",
type: "POST",
data: JSON.stringify(jsondata),
dataType: 'json',
async: false,
success: function (result) {
$("#div1").html(result);
},
error: function (error) {
//$("#div1").html(error);
console.log("Something went wrong", error);
}
});
console.log(JSON.stringify(jsondata));
});
});
【问题讨论】:
-
你试过用url https://api-xxx.azurewebsites.net/api/demo/1234567吗?
-
@TomSun:是的,从服务器完美运行,只有 Ajax 请求会导致问题。
-
据我所知,如果我们在 Azure WebApp 门户中设置 CORS *,则无需在代码中设置。如果可以接受,您可以从代码中删除 CORS 设置并重试。
标签: jquery ajax azure cors azure-web-app-service