程序go 2015-05-05 12:47 采纳率: 100%
浏览 199

在.ajax POST中启用CORS

I've created an .ajax request, but I keep receiving this error:

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.

I've looked a few things online and edited my ajax request to look like this:

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)
    }
});

Is there anything that I am missing from my request?

I've seen this SO q/a but I'm not sure if I'm doing the right thing or if this is relevant to my issue.

I'd appreciate any suggestions. Thanks in advance.

UPDATE: Just tried enabling CORS in the web.config file according to this, but nothing changed. Will update again.

UPDATE 2: Adding this to the section of web.config appears to have solved my issue:

<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>
  • 写回答

2条回答 默认 最新

  • weixin_33675507 2015-05-05 12:52
    关注

    Fixed this very same issue a while back. And I did not need to enable/activate CORS as I've read that some firewalls will strip out the headers for security. http://promincproductions.com/blog/server-proxy-for-cross-site-scripting-cors/

    In a global part of your js code, add in a function ...

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

    Then, to the URL in your AJAX (GET assumed?) request, if you have no URI params, append ?callback=googleDocCallback

    and if you do have other params, append &callback=googleDocCallback

    For more info, please see: https://jvaneyck.wordpress.com/2014/01/07/cross-domain-requests-in-javascript/

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败