Reputation: 11915
I am trying to send an ajax request from my localhost development box to a server using
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
format: "JSON",
season: "2015REG"
// Request parameters
};
$.ajax({
url: "https://<mysite>/sub/" + params.format + "/" + params.season,
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","<mykey>");
},
type: "GET"
})
.done(function(data) {
alert("success");
console.log("Data: \n" + JSON.stringify(data));
})
.fail(function(error) {
alert("error");
console.log("Error" + JSON.stringify(error));
});
});
</script>
</body>
</html>
when I look into firefox i see that it is actually sending an OPTIONS request - which is not responded to by the server (404 not found) , so I then get a Cross-Origin Request blocked error.
OPTIONS
XHR
https://mysite [HTTP/1.1 404 Resource Not Found 2437ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mysite (Reason: CORS header 'Access-Control-Allow-Origin' missing).
What am I doing wrong? Why is jquery trying to ask for options when I am explicitly sending a GET? Also, I don't own this server, its another company, that has a subscription API, so I can't give out the key or anything to help troubleshoot.
Upvotes: 4
Views: 1873
Reputation: 98921
If the other server is yours, you can enable cors
Otherwise you cannot (in most cases*) make requests to a foreign domain via ajax
JavaScript and the web programming has grown by leaps and bounds over the years, but the same-origin policy still remains. This prevents JavaScript from making requests across domain boundaries, and has spawned various hacks for making cross-domain requests.
CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed. CORS continues the spirit of the open web by bringing API access to all.
One way to bypass CORS is using whateverorigin.org, here's an example.
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){
alert(data.contents);
});
Upvotes: 1
Reputation: 1
Preflight (that's what is happening) for CORS is done when
In your case, your custom header is triggering the preflight
Effectively, your CORS request is being rejected by the server. From what you've posted, you need a custom header in the request, therefore the remote server needs to handle the preflight requests if it is to offer CORS resources
It's possible the server you are trying to use has not been set up to allow client (browser) connections, only "server" connections which do not have cross origin restrictions
Upvotes: 1