Dean.DePue Dean.DePue - 3 years ago 89
Ajax Question

Strange response with AJAX call to another domain

I am making an AJAX call when an MVC partial view is opened to fill a dropdown. This connection is to one of our contractors (whom I have called and they are trying to help). This is the call:

$.ajax({
async: true,
crossDomain: true,
url: "https://contactor/integration_beta/reports?request=getStandardList",
type: 'POST',
headers: {
"authorization": "Basic MzY0MTVlYTktNDJjZC00ZGI1LTg1OWItNjFiODM1MzEwNzY1OjY1MDhkM2U4LTlmYTItNGE2Ny05NmYwLTgwZTgxMGY5NWNjNQ==",
"Access-Control-Allow-Origin": "*",
"content-type": "application/json"
},
processData:false,
data: { version : 1.0 },// "{\n \"version\": \"1.0\"\n}",
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = errorThrown;
alert('error, ' + errorThrown);
},
success: function (data) {
var d = data;
alert('success, ' + data);
$("#txtReportStatus").val(data);
}
});


The problem is that I am getting a 200 response:

enter image description here

But the console is showing an error:

enter image description here

Does anyone have any idea of what I am doing wrong here?

Answer Source

Cross-origin policies have to be set on the server receiving the request, not the one making it (i.e. your application). The error is telling you that the contractor's server does not allow requests from localhost, which is probably the way it's going to have to remain. Otherwise, anyone could create a local website that could access the API remotely.

For your development purposes, you'll need to find an alternate means to circumvent the CORS protection. Since CORS is actually enforced client-side by the browser to protect you, you can disable this protection without involving the third-party. For Chrome, you can use an extension like Allow-Control-Allow-Origin: *. There's also generally a config option to start the browser without CORS for testing. In Chrome, again, you can use the --disable-web-security command-line flag when starting Chrome. Make sure to only do this when developing, as you're disabling browser security and could end up compromising yourself if you're just browsing the web. An extension is probably better for this, as a result.

As for other browsers, I'm sure there's similar functionality to be had, but I use Chrome for development, so I don't have specifics for anything else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download