在 .ajax POST 中启用 CORS

Enabling CORS in .ajax POST

我创建了一个 .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>

不久前解决了这个非常相同的问题。而且我不需要 enable/activate CORS,因为我读到一些防火墙会为了安全而去掉 headers。 http://promincproductions.com/blog/server-proxy-for-cross-site-scripting-cors/

在您的 js 代码的全局部分,添加一个函数...

window.googleDocCallback = function () { return true; };

然后,对于您的 AJAX(GET 假设?)请求中的 URL,如果您没有 URI 参数,请附加 ?callback=googleDocCallback

如果您还有其他参数,请附加 &callback=googleDocCallback

详情请见:https://jvaneyck.wordpress.com/2014/01/07/cross-domain-requests-in-javascript/

我有同样的问题,我在我的服务器端代码解决了这个问题,而不是在 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");