Access to restricted URI denied" code: "1012 [Break On This Error]
xhttp.send(null);
function getXML(xml_file) {
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest(); // Cretes a instantce of XMLHttpRequest object
}
else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP"); // for IE 5/6
}
xhttp.open("GET",xml_file,false);
xhttp.send(null);
var xmlDoc = xhttp.responseXML;
return (xmlDoc);
}
I'm trying to get data from a XML file using JavaScript. Im using Firebug to test and debug on Firefox.
The above error is what I'm getting. It works in other places i used the same before, why is acting weird here?
Can someone help me why it's occuring?
Update:
http://jquery-howto.blogspot.com/2008/12/access-to-restricted-uri-denied-code.html
I found this link explaining the cause of the problem. But I didn't get what the solution given means can someone elaborate?
Another possible cause of this is when you are working with a .html file directly on the file system. For example, if you're accessing it using this url in your browser: C:/Users/Someguy/Desktop/MyProject/index.html
If that then has to make an ajax request, the ajax request will fail because ajax requests to the filesystem are restricted. To fix this, setup a webserver that points localhost to C:/Users/Someguy/Desktop/MyProject and access it from http://localhost/index.html
Sounds like you are breaking the same origin policy.
Sub domains, different ports, different protocols are considered different domains.
Try adding Access-Control-Allow-Origin:* header to the server side script that feeds you the XML. If you don't do it in PHP (where you can use header()) and try to read a raw XML file, you probably have to set the header in a .htaccess file by adding Header set Access-Control-Allow-Origin "*". In addition you might need to add Access-Control-Allow-Headers:*.
Also I'd recommend to replace the * in production mode to disallow everybody from reading your data and instead add your own url there.
Without code impossible to say, but you could be running foul of the cross-site ajax limitation: you cannot make ajax requests to other domains.
Related
when i tried to convert image url to base64 am getting CORS issue.
Not sure what exactly need to do to get rid of this CORS issue
my code look like this
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.dropbox.com/******/gradient-test.jpg?dl=1', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
am getting this error
Access to XMLHttpRequest at 'https://www.dropbox.com/****/gradient-test.jpg?dl=1' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.**
and am not able to console ,since CORS issue.
Can any guys help me to get rid with an jsfiddle or an live example
The CORS issue you are facing is because you are trying to access the www.dropbox.com domain from a different domain. The short answer is that you can't fix this from your own domain--it requires cooperation from the www.dropbox.com domain to fix this. You are the client in this case, and dropbox is the server, so as a client you can't tell the server what security settings to use. The server can opt in and could configure their site to allow your origin, but that isn't something dropbox is likely to do. You'll need to re-architect your approach. (also see Ways to circumvent the same-origin policy if you don't believe me when I say you need to re-architect your approach.)
Check out https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more background:
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from unless the response from other origins
includes the right CORS headers.
You could try using JavaScript to inject a script tag into your DOM that sets the type of the script tag to something other than JavaScript. Then you could have your code read the contents of that and make use of it...but that is a completely re-architected approach. See How does HTML tags work inside script tag? and https://stackoverflow.com/a/8578840/230055 if you want to look into that.
I'm trying to hack my back-end, which exposes a REST API. The worst thing that can happen to my database according to firefox CORS policy is that I can create a new object with POST request, as it does not need a preflight. This is the simple code (I'm running it via jsfiddle, but it shouldn't mean a thing)
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:8000/api/v1/company", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.send('{description:"This company was added by pure hacking"}');
But I'm getting an error in the console:
Blocked loading mixed active content "http://127.0.0.1:8000/api/v1/company"
The error is not because of SOP, its a mixed content error, that is making an http request on a https page.
jsfiddle defaults to https but allows http, but only on saved fiddles.
Change the url of your fiddle to use http instead of https
I run a service where there is a javascript file that is called and self executed on a user's site.
This then calls an external server every 10 or so seconds with a bunch of variables.
I used to do this by using a createElement('script') and then setting the path to a file on the external server and passing the required variables across by means of GET variables. (works well for small URI's)
This worked really well and seemed to work cross browser as well with no undesired effects.
The problem I then ran into was when I needed to extend the amount or size of the variables that were being sent across. So obviously I decided to change from GET method to POST, but by doing that I could no longer use the createElement('script') trick and had to opt for the XMLHttpRequest() (ala Ajax - without jQuery) method which worked really well, except for the minor problem of having to also cater for Internet Explorer and Opera which didn't really play ball too well (big shock). So I used the following:
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("post", "http://xx.xxxx.com/");
if (request){
request.onload = function(){
//do something with request.responseText
};
request.send(myPostObjectDataVariableGoeshere);
}
..which I found over at this page
This is basically just a fallback to using the XDomainRequest() method which InternetExplorer wants you to use instead..
Fantastic, BUT -> Looking in the Console of Developer Tools in IE it says:
SEC7118: XMLHttpRequest for http://xx.xxxx.com/ required Cross Origin Resource Sharing (CORS).
SEC7120: Origin null not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
But what's really odd about this is that I've already got the following as the first line in my backend PHP file that is being called (which works for other browsers...)
header('Access-Control-Allow-Origin: *');
Someone please tell me what's wrong here.. Also if there is a better way to be doing this instead of fighting the browser wars..
Note: I cannot use jQuery for this task!
You should try jQuery for this task. Its much easier and don't have that problem with IE.
http://api.jquery.com/jQuery.ajax/
IE unfortunately block Cross Origin requests, i believe there is no simple way to get around it by script only, but you can try tuning the options or via my proxy script.
Tuning the options
Internet Explorer ignores Access-Control-Allow headers and by default prohibits cross-origin access for Internet Zone. To enable CORS go to Tools->Internet Options->Security tab, click on “Custom Level” button. Find the Miscellaneous -> Access data sources across domains setting and select “Enable” option.
Proxy Script on local server as a Bridge
Previous post:
Remote POST request with jQuery and Ajax
This is for you to place a PHP script on a local server and do a local AJAX request and proxy to the remote server for good.
I am working on a site, where i need to check if a CSS file on a remote host exists or not and then load the local copy of the same CSS file, if it doesn't exists.
Code on which I am working,
<script>
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
function AddLocalCss(){ document.write('<link rel="stylesheet" type="text/css" href="css/html5-reset.min.css">') }
</script>
<script>!UrlExists('http://meyerweb.com/eric/tools/css/reset/reset.css') && AddLocalCss();</script>
But this throws an error, (when checked in Chrome Developer tools)
XMLHttpRequest cannot load http://meyerweb.com/eric/tools/css/reset/reset.css. Origin http://example.com is not allowed by Access-Control-Allow-Origin.
Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101
Can anyone please suggest a solution or a workaround to achieve this?
you can use some of the functionality of this post: Dynamically loading css file using javascript with callback without jQuery, you can use straight that function.
I hope this would help
XHR is limited by Same Origin Policy - you can't request resources from another domain/protocol without jumping extra hoops. You must either request remote server to set up CORS or don't use XHR at all.
Instead of it you can just generate a link element and watch either its state or state of other elements that loaded style would affect. Unfortunately this behavior is not standartized across browsers, but, fortunately, there are some libraries to simplify dealing with it. Check out Ensure.
Help me understand AJAX and cross-site scripting a little better. Writing AJAX is fairly straight forward. If I want to asynchronously read HTTP header of a website, I'd do something like this:
var req = new XMLHttpRequest();
req.open('HEAD', 'http://www.stackoverflow.com/', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
else
alert("Error loading page");
}
};
req.send(null);
However, when I copy and paste this into a simple HTML page using notepad and try to run it locally, the request status doesn't seem to return 200. I am assuming this is due to cross-site scripting. How would I get around this?
You are right in that making requests across domains is not allowed unless you are using Cross-Origin Resource Sharing (CORS, http://www.w3.org/TR/cors/). CORS has a client-side and server side component. On the client side, the request looks mostly like a regular XmlHttpRequest, except you have a few other properties and handlers you can configure. On the server, the response will need to emit some special http headers. This article gives a good breakdown of how CORS works on the client and server: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
My first guess would be to try and make a local PHP file which acts like a gateway:
<?php
echo get_headers($_GET['url']);
?>
Then, perform a GET request with the url of your target site as the parameter, and parse the .responseText of that request to determine the response header of your original.
I don't think it's possible with pure JS, so you'll have to use some serverside code.
There are two types of "locally":
Using a local server (http://localhost/)
Accessing HTML file directly (file:///C:\a\b\c.html)
AJAX won't work, ever, in the second case.
You can't make an ajax request to http://stackoverflow.com if your page is being served on http://localhost/...
http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests