【发布时间】:2015-07-15 05:06:49
【问题描述】:
我创建了一个 .ajax 请求,但我不断收到此错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.com/api/GetData. This can be fixed by moving the resource to the same domain or enabling CORS.
我在网上查看了一些东西并将我的 ajax 请求编辑为如下所示:
var url = "https://api.com/api/GetData";
var data = jsonHandler();
$.support.cors = true;
this.xhr = $.ajax({
crossDomain: true,
url: url,
type: "POST",
data: data,
accept: "application/json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response);
},
error: function(response) {
console.log(response)
},
fail: function(response) {
console.log(response)
}
});
我的请求中有什么遗漏吗?
我见过this SO q/a,但我不确定我做的是否正确,或者这是否与我的问题有关。
如果有任何建议,我将不胜感激。提前致谢。
更新:刚刚尝试根据this在web.config文件中启用CORS,但没有任何改变。将再次更新。
更新 2: 将此添加到 web.config 部分似乎解决了我的问题:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Authorization, Origin, X-Requested-With, Content-Type, Accept"/>
</customHeaders>
</httpProtocol>
【问题讨论】:
-
您确定接收 API 接受 CORS 请求吗?
-
@RoryMcCrossan 啊哈.. 嗯,最好去检查一下。可能不得不删除这个帖子。谢谢。
-
该服务器应该设置'access-control-allow-origin'标头
-
@terbubbs 服务器必须指定它允许来自哪里的 CORS 请求
标签: javascript jquery ajax json cors