简体   繁体   中英

Enabling CORS in .ajax POST

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>

I have the same problem, I solved this issue at my server side code, not in the ajax request. in my case; I am using cakePHP at server side.

I added this code to my php controller.

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM