I know the title is contradictory but bear with me.
I have a simple XMLHttpRequest in an MVC app hosted on Azure:-
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET","http://isni.oclc.org/sru/DB=1.2/query=pica.na+%3DPrince",
false);
xhttp.send();
</script>
this results in a 200 code response and I can see the return page (XML data) using Chrome Network panel. However, I also get the following 2 errors (in the Chrome Console):-
1) Failed to load http://isni.oclc.org/sru/DB=1.2/?query=pica.na+%3DPrince: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mhdatamodel.azurewebsites.net' is therefore not allowed access.
loadDoc # HttpRequest:153
onclick # HttpRequest:89
2) Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://isni.oclc.org/sru/DB=1.2/?query=pica.na+%3DPrince'.
My question is how did I get exactly the response I was expecting (the XML data, the same as if I had just entered the http://... into my browser) and yet get a "Failed to load..." and a "Failed to execute 'send'..." error?
Thanks in advance
Related
My code is relatively simple. I have a URL, which is defined before the request is sent, I then have a $.get() request, which I expect to return back a JSON object. The code is below.
var url = "url"; //Removed for clarity
$.get(url, function (data) {
alert("hi");
});
The url being used within the request is correct. I have copied and pasted the code into my browser and I receive the response that I expect from the endpoint.
However when this JQuery code is executed, the callback function is not called and the alert is not fired. Why is this happening?
Edit: Forgot to post the error message I found in the console.
I'm receiving this:
2Initial%20Loan#:1 Access to XMLHttpRequest at
'-snip url-' from
origin 'https://localhost:44358' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Will it have anything to do with the GET request not working?
There might be some problem with the url. The syntax specified by you is correct and the same is checked
var url = "https://jsfiddle.net/"; //Removed for clarity
$.get(url, function (data) {
alert("hi");
});
working code
This is a classic example of CORS, which stands for Cross origin resource sharing. Browsers prevent sending AJAX request to domain other than where the javascript file originated from.
As the error message says you have to set 'Access-Control-Allow-Origin' http response header from your server code. Read more about CORS here [enter link description here CORS MDN
I'm trying to connect to google with a simple get request through JS and it seems to always be giving me the same error.
"Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://google.com'."
Any clue why this would be happening? Relevant code is below.
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://google.com", false);
try {
xmlHttp.send();
} catch (err) {
alert("EXCEPTION: " + err.message);
}
alert("here's the result of the get: " + xmlHttp.responseText);
This is simply a cross-origin permission failure, due to the same origin policy. If you ran this same request asynchronously and looked in your console, you'd see the much more helpful error message:
XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[whatever]' is therefore not allowed access.
This is because only scripts run on pages from http://www.google.com may read resources from http://www.google.com. If the resource being fetched served appropriate CORS headers (e.g., Access-Control-Allow-Origin), you would not see this error. (However, http://www.google.com serves no such headers).
My code:
var answer_array = [];
var req = new XMLHttpRequest();
req.onload = function() {
answer_array = answer_array.concat(JSON.parse(this.responseText).results);
console.log(answer_array);
}
req.open("GET", "https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13");
req.setRequestHeader("authorization", "Basic Base64 encoded credentials");
req.setRequestHeader("cache-control", "no-cache");
req.setRequestHeader("postman-token", "b94725ff-408b-c82e-a985-6c38feb380af");
req.send();
This is what is in my console:
scripts2.js:22 OPTIONS https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13 (anonymous function) # scripts2.js:22
2015-10-21 12:41:09.059 index.html:1 XMLHttpRequest cannot load https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
When I go to the network tab on Chrome I see this:
gpsdata?fromdate=2015-10-13 OPTIONS 405 xhr scripts2.js:22 0 B 452 ms
This error message:
No 'Access-Control-Allow-Origin' header is present on the requested resource
means that you are running into a cross origin permission issue which means that you are trying to access a site that does not permit access from the domain that your page is on. If your page is on your local drive being accessed with a file:// URL, then the first thing you can do is to put it on an actual web server and try it there since file:// URLs have some additional restrictions on them.
If that doesn't work either, then the issue is that the api.comettracker.com site is not allowing access from your particular site.
When I put your code into a jsFiddle and try it there and look at the network trace, what I see there is that the OPTIONS method which is used to pre-flight a cross origin request is being rejected by api.comettracker.com which tells the browser the cross origin request as currently formatted is not permitted.
I get a different error if your custom headers are removed from the request so I think that there's something incorrect about your custom headers. Since I don't know that particular API, don't have your access credentials or know how to use them, I don't know what exactly to suggest for the headers, but I think that's the place to start.
I know a lot of code, but I'm a complete scrub when it comes to xhr.setRequestHeader in html. I've set it up so a user can be logged in using Mozilla's Persona log in, but the console always returns errors:
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
[Error] Failed to load resource: the server responded with a status of 405 (Method Not Allowed) (sign-in, line 0)
I've set up the html pages... somewhat, but I'd love some help. my website can be found at https://agstp.tk and https://github.com/August712/august712.github.io. Thanks!
(Oh, and can someone explain to me what a header is? As I said, I'm new to this.)
I have my own node.js written in C. When I open the browser and browse to 192.168.0.150:8000/index and call the script:
var socket = io.connect("/index");
socket.on('connect', function() {
$('#onindex').addClass('connected');
});
every thing is OK.
BUT:
When I try to:
var socket = new io.Socket('192.168.0.150', {port: 8000 });
socket.connect("/index.html");
I get the following error on the Javascript console:
XMLHttpRequest cannot load 192.168.0.150/index.html:80/socket.io/xhr-polling//…. Origin null is not allowed by Access-Control-Allow-Origin.
This indicates to me that the server can't find it.
How can I fake the JS to think I'm browsing?
Let's break down your error message
XMLHttpRequest
The problem was with XMLHttpRequest (on the side running the script)
cannot load 192.168.0.150/index.html:80/socket.io/xhr-polling//….
it couldn't load the page
Origin null is not allowed by Access-Control-Allow-Origin.
because it is not allowed to by Access-Control-Allow-Origin settings preventing an origin of null.
You can read up about access control here on MDN. An origin of null can arise from a page located on a data URI or using the file: protocol. This is part of the same-origin policy which you can read about here. You may have to set up CORS on your server to get it to work.