Failed to execute 'send' on 'XMLHttpRequest' Syncronous - javascript

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).

Related

XMLHttpRequest loads but fails to load

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

GET JSON with XMLHttpRequest

I have a python script which generates a JSON and I can see it in http://192.168.1.171:17000/
In the Network tab I get
200 GET / 192.168.1.171:17000 json transfereed 40KB
When I'm trying to GET it from another webpage with javascript
var url = "http://192.168.1.171:17000";
var Httpreq = new XMLHttpRequest();
function Get(url){
Httpreq.open("GET", url, false);
//Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
Httpreq.send(null);
return Httpreq.responseText;
}
var json_obj = JSON.parse(Get(url));
console.log("data: "+json_obj);
in the network tab I get
200 GET / 192.168.1.171:17000 json transfereed 0KB
it's Response tab
SyntaxError:
JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
and in the console
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
NS_ERROR_FAILURE:
When I add
Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
instead of fixing the problem I'm getting one more error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS request failed).
When I visit http://192.168.1.171:17000/ I'm getting my json, which is valid, and when I run my javascript code with another json it runs. But when I run my javascript code with my json it doesn't run. Could you please help me to understand what I'm doing wrong here?
That header needs to be added to the server's response, not the client's request. In other words, you need to modify your Python app to return the Access-Control-Allow-Origin header. (How exactly you do that depends on what you're using on the Python side.)

What is wrong with my HTTP over AJAX (javascript)

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.

response not getting with the header in javascript

I'm new to AJAX and I have the following code:
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader('Access-Control-Allow-Credentials')));
}
};
xhr.send();
}
get_filesize("http://fileraja.com/download/?songURL=./Tamil/K/Kaththi_160kbps/Pakkam_Vanthu-StarMusiQ.Com.mp3", function(size) {
var estimatedtime = (new Date().getTime())/size;
var time = new Date(estimatedtime);
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
});
When I run this code, I get an error like:
XMLHttpRequest cannot load http://fileraja.com/download/?songURL=./Tamil/K/Kaththi_160kbps/Pakkam_Vanthu-StarMusiQ.Com.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After some research, I have found that it's due to the CORS policy, so I tried adding the code xhr.setRequestHeader("Access-Control-Allow-Credentials",true);, but it didn't help me.
How can I get rid of this error?
After some search i have found that its due to CORS policy...so i have tried adding the code...
You can't do anything client-side that will change the CORS policy of the server. This is the point of the SOP and CORS: The server determines whether to allow any particular client to grab its content via ajax.
So unless http://fileraja.com are willing to add the relevant CORS headers at their end, you simply cannot do cross-origin requests to their domain with ajax. You might ask them, or ask if they offer a JSONP API (JSONP isn't subject to the SOP, because it's not ajax). Otherwise, you'll have to use a server of your own to proxy the request.
This error is because of the CORS(Cross Origin Resource Sharing) Policy which does not allow requests that do not arise from the same origin. A header Access-Control-Allow-Headers: * can be set at the resource to allow all requests.
Other methods include JSONP as mentioned by T.J Crowder and the same server for proxy request.
This might be a good read CORS and POST Request

What causes EventSource to trigger an error in my Chrome extension?

I have the following code in a background_script in a Google Chrome extension:
var source = new EventSource("http://www.janywer.freetzi.com/events/groupshout.php");
source.addEventListener('message', function (e) {
console.log('message', e.data);
}, false);
source.addEventListener('open', function (e) {
console.log('open');
}, false);
source.addEventListener('error', function (e) {
console.log('error')
}, false);
My problem is the following: Whenever I load the extension, it's saying 'error', but how do I find out what exactly triggered the error?
The specification defines only a few possible cases for the "error" event to be triggered, which are:
A cross-origin request was initiated, but the expected CORS headers were not received. This includes:
Access-Control-Allow-Origin is not set or does not match the origin URL.
You've set withCredentials:true (via the second parameter of EventSource), but the server did not reply with Access-Control-Allow-Credentials: true.
A network error has occurred.
The http status is not 200, 305, 401, 407, 301, 302, 303 or 307.
The user agent (browser) is trying to re-establish a connection.
The http status is 200, but the Content-Type header of the response is not `text/event-stream.
A redirect occurred, which resulted in one one the previous conditions.
When a CORS error occurs, Chrome will usually log the following message to the console:
EventSource cannot load http://example.com/eventsource. Origin http://origin.example.com is not allowed by Access-Control-Allow-Origin.
For some reason, Chrome does not show this error when a redirect has taken place.
You have probably added the "http://www.janywer.freetzi.com/*" permission to your manifest file, causing the initial request to pass. This page redirects to a different domain (without www-prefix). You have probably not added this domain to your manifest file, so Chrome attempts a CORS-enabled request. The expected headers are not received, so Chrome aborts the request.
This can be solved in two ways:
Add all involved domains to your
file, e.g.
"permissions": [
"http://www.janywer.freetzi.com/*",
"http://janywer.freetzi.com/*"
]
(see match patterns in the Chrome extension documentation)
or let the server reply with the expected CORS headers. In PHP:
header("Access-Control-Allow-Origin: *");
This allows any page to access your URL. To restrict access to your extension only, use:
header("Access-Control-Allow-Origin: chrome-extension://EXTENSION ID HERE");

Categories