Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 759
terbubbs Avatar asked May 05 '15 12:05

terbubbs


1 Answers

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");
like image 183
ErasmoOliveira Avatar answered Oct 21 '22 22:10

ErasmoOliveira