ter*_*bbs 5 javascript ajax jquery json cors
我已经创建了一个.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.
Run Code Online (Sandbox Code Playgroud)
我在网上看了一些东西并编辑了我的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)
}
});
Run Code Online (Sandbox Code Playgroud)
我的请求中是否有任何遗漏?
我已经看到了这个SO q/a,但我不确定我是做正确的事还是我的问题.
我很感激任何建议.提前致谢.
更新:只是试图按照使CORS在web.config文件中这个,但没有任何改变.将再次更新.
更新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>
Run Code Online (Sandbox Code Playgroud)
我有同样的问题,我在服务器端代码解决了这个问题,而不是在ajax请求中.就我而言; 我cakePHP在服务器端使用.
我将此代码添加到我的php控制器中.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept");
Run Code Online (Sandbox Code Playgroud)