XHR to same domain being blocked - ajax

I'm having a pretty weird problem with CORS on a webapp I'm trying to make
I'm using Servlets (Tomcat8.0) for the backend. It's a school project, so I can't use a framework
A GET request to http://localhost:8080/FileBox/dashboard
returns a JSON payload( plain json, not jsonp,which I could use, but its the same domain). I'm using ajax to make the XHR, but it's being blocked by chrome as CORS
Should this be happening, since I'm making the XHR from the same domain(host+port)
'localhost:8080/FileBox/dashboard.jsp'
to
'localhost:8080/FileBox/dashboard'
Please, and thank you for the help!

You aren't making a request to http://localhost:8080/FileBox/dashboard. The error message says you are making a cross-origin request using an unsupported scheme and that http is a supported scheme.
Presumably you have made the two mistakes of:
Getting the URL wrong
You should be using a relative URL:
/FileBox/dashboard
but are trying to use an absolute URL:
http://localhost:8080/FileBox/dashboard
but have typed it wrong and are actually requesting
localhost:8080/FileBox/dashboard
Not loading the page over HTTP to start with
Possibly by double clicking the file in your system file manager, you have bypassed your HTTP server and are loading something like file:///c:/users/you/yourproject/index.html
Combined with the previous mistake, you end up trying to request file:///c:/users/you/yourproject/localhost:8080/FileBox/dashboard, with Ajax and get a security violation.
Solution
Fix the URL to be a proper relative URL
Point your browser at http://localhost:8080 instead of double clicking files in your file manager

Related

Angular JS $http request does not reach the server in ie8

I'm having issues with using $http on ie8. The request does not reach the server, until I hit a refresh. Coming back to the same link still has the same problem until I hit refresh again.
The weird thing is if the web server is on LAN and the request is made to a server in LAN, it works fine. But if the webserver is hosted remotely, it does not work!
Here is the code:
Index.html
{{test}}
Controller
app.controller(
"TestController",
function( $scope, $http) {
var url = '/test/get_data';
$http.get(url).success(function(data) {
$scope.test = data;
});
}
);
I got this error: TypeError: Object doesn't support this property or methodundefined
I prepared a JSFiddle earlier but JSFiddle is broken in ie8 so I don't provide it here.
Unfortunately I don't have a remote server that I can share with you.
Edit
Previously I used an external url which gave me 'Access Denied' error in ie because of Same Origin Policy as mentioned by one answer below. But this was not my original problem. I still have the issue above when request is from the same origin
This is a cross domain request, which is not allowed in ajax because of Same Origin Policy.
There are two solutions for this
1. JSONP: It is a cross browser way to handle cross domain ajax requests using javascript callback mechanism
2. CORS: It is a HTML5 standard, it is implemented by most of the modern browsers except IE
Mongodb lab is not supporting jsonp since it has support for CORS, that is why your request is failing in IE and works in Chrome and other browsers.
As per this post they do not have any plan to support jsonp, so I don't thick there is a way to make this work in IE.
So I found the fix... Hope this helps anyone out there that experience this problem
Angular script needs to be loaded after jQuery. I didn't have this because Yii framework that I use autoloads jQuery and the angular was not included after the jQuery.
All the controller functions need to be at the end of body section (just before the closing )
Updating to angular 1.0.5 seems to fix the problem. The problem occurred in 1.0.4 with all the above tricks. I think is related to fix 791804bd

cross domain request with dojo

I am attempting a cross domain request with dojo. External url is of MIME type text/html the only content on the page is something like 1236. I tried
dojo.require("dojo.io.script");
dojo.ready(function() {
dojo.io.script.get({
url: "theexternalurl",
callbackParamName: "jsoncallback",
load: function(data) {
console.log(data);
}
});
});,
But that was no good. Any ideas on how this can be done with dojo?
I suspect you are bumping into the browser security here. Cross-domain requests will only work when using iframes or injecting scripts (as you have done) and when the content of that script is valid "text/javascript".
If you are trying to load "text/html" into the script, it won't work as it isn't a valid script. It is something most of us have tried to do at some point. I have spent hours trying to get around cross-domain restrictions and found the security blocking it to be solid.
See my answer here for more details.
If all you are trying to do is load the content onto the page then you could use an <iframe>. However, if you are trying to parse the loaded content in some way than I'm afraid it is a dead-end. Probably not the answer you were hoping for but it'll save you hours of frustration.

xhrPost : from an http view to an https url

using Dojo, is it possible to make an Ajax call using xhrPost from an HTTP view to a HTTPS url ?
The url must be HTTPS (as defined in Struts).
If I simply set "MyCommand" as the 'url' parameter of the xhrGet, I get a 302 error code.
If I transform "MyCommand" using javascript to something like "https://......./servlet/MyCommand" I see the following error in Firebug : "uncaught exception: Permission denied to call method XMLHttpRequest.open".
I'm stuck using both approaches, the only solution I found is to remove the "https" clause in the struts configuration file, and of course this is not a correct solution :)
Thanks for any help.
Best regards,
Nils
connection to https from http involves a different port of the target. This violates the same-origin policy which should be enforced by the browser to the running javascript code.
It should work with an iframe..
dojo.io.iframe encapsulates this behaviour for you
http://docs.dojocampus.org/dojo/io/iframe
If your server responds with a redirect to a non-ssl (correctly to same-origin) page you should be able to read the response (because the iframe is now in the same-origin).

NETWORK_ERROR: XMLHttpRequest Exception 101

I am getting this Error
NETWORK_ERROR: XMLHttpRequest Exception 101
when trying to get XML content from one site.
Here is my code:
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
xmlhttp.onReadyStateChange=function() {
if(xmlhttp.readyState==4) {
var value =xmlhttp.responseXML;
alert(value);
}
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
//alert(xmlhttp.responseXML);
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
Does any one have a solution?
If the url you provide is located externally to your server, and the server has not allowed you to send requests, you have permission problems. You cannot access data from another server with a XMLHttpRequest, without the server explicitly allowing you to do so.
Update: Realizing this is now visible as an answer on Google, I tried to find some documentation on this error. That was surprisingly hard.
This article though, has some background info and steps to resolve. Specifically, it mentions this error here:
As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown
An interpretation of INVALID_ACCESS_ERR seems to be what we're looking at here.
To solve this, the server that receives the request, must be configured to allow the origin. This is described in more details at Mozilla.
The restriction that you cannot access data from another server with a XMLHttpRequest can apply even if the url just implies a remote server.
So:
url = "http://www.myserver.com/webpage.html"
may fail,
but:
url = "/webpage.html"
succeed - even if the request is being made from www.myserver.com
Request aborted because it was cached or previously requested? It seems the XMLHttpRequest Exception 101 error can be thrown for several reasons. I've found that it occurs when I send an XMLHttpRequest with the same URL more than one time. (Changing the URL by appending a cache defeating nonsense string to the end of the URL allows the request to be repeated. -- I wasn't intending to repeat the request, but events in the program caused it to happen and resulted in this exception).
Not returning the correct responseText or responseXML in the event of a repeated request is a bug (probably webKit).
When this exception occurred, I did get an onload event with readyState==4 and the request object state=0 and responseText=="" and responseXML==null. This was a cross domain request, which the server permits.
This was on an Android 2.3.5 system which uses webKit/533.1
Anyone have documentation on what the exception is supposed to mean?
Something like this happened with me when I returned incorrect XML (I put an attribute in the root node). In case this helps anyone.
xmlhttp.open("GET",url, true);
set the async part to true
I found a very nice article with 2 diferent solutions.
The first one implementing jQuery and JSONP, explaining how simple it is.
The second approach, it's redirecting trough a PHP call. Very simple and very nice.
http://mayten.com.ar/blog/42-ajax-cross-domain
Another modern method of solving this problem is Cross Origin Ressource Sharing.
HTML5 offers this feature. You can "wrap" your XMLhttp request in this CORS_request and
if the target browser supports this feature, you can use it and wont have no problems.
EDIT:
Additionaly i have to add that there are many reasons which can cause this Issue.
Not only a Cross Domain Restriction but also simply wrong Settings in your WEB.CONFIG of your Webservice.
Example IIS(.NET):
To enable HTTP access from external sources ( in my case a compiled Phonegap app with CORS request ) you have to add this to your WEB.CONFIG
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Another scenario:
I got two webservices running... One on Port 80 and one on Port 90. This also gave me an XML HTTP Request Error. I even dont know why :). Nevertheless i think this can help many not well experienced readers.

Can I use XMLHttpRequest on a different port from a script file loaded from that port?

I have website that use XMLHttpRequest (jQuery, actually). I also have another site running on the same server, which serves a script file that makes XHR requests back to THAT site, ie.
http://mysite:50000/index.html includes
<script src="http://mysite:9000/otherscript.js"></script>
and http://mysite:9000/otherscript.js includes
$.ajax({
url: 'http://mysite:9000/ajax/stuff'
});
The problem is - this doesn't work. The AJAX requests from the loaded script simply fail with no error message. From what I've been able to find this is the old same origin policy. Given that I control both sites, is there anything I can do to make this work? The "document.domain" trick doesn't seem to do a thing for XMLHttpRequest.
Nope- can't do this with XHR. Same-domain policy is very restrictive there- same host, same port, same protocol. Sorry! You'll have to resort to other tricks (iframes, title manipulation, etc) to get it to work.
You can do this by adding Access-Control-Allow-Origin header.
If you are using PHP
header("Access-Control-Allow-Origin: http://example.com");
or in Node.js
response.writeHead(200, {'Access-Control-Allow-Origin':' http://example.com'});
This should do the trick for you. It always works for me.
I just solved a similar issue with a PHP service I'm currently playing around with (not sure how relevant a PHP solution is to this directly, but...) by making a single line proxy PHP page, SimpleProxy.php:
<?php
echo file_get_contents('http://localhost:4567');
?>
And in my XMLHttpRequest I use 'SimpleProxy.php' in place of 'http://localhost:4567', which effectively puts the request on the same domain as my .js code.

Resources