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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With