I am trying to read xml file on the internet.It works on IE but does not on Firefox/Chrome.
It gives the error below on Firefox;
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://xxxxx.com/YYYY.xml. This can be fixed by moving the resource to the same domain or enabling CORS.
Here is my code;
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
xml = loadXMLDoc("http://xxxxx.com/YYYY.xml");
...........
.........
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
It returns null on the line
xhttp.responseXML;
in the loadXMLDoc function.
After getting this error I googled the error and tried the code below which makes CORS request. But it also does now work.
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://xxxxx.com/YYYY.xml';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
In makeCorsRequest() function, after createCORSRequest() function, xhr.responseText is "" and xhr.ResponseXML is null.In response handler, it gives xhr.onerror.
Could you help me about this error?
Thanks.
UPDATE:
I am trying to test my pages in my computer(localhost). On the IIS in my computer, I enabled the CORS with the web.config below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
On the network tab of the developer tab of Firefox
http://imgur.com/CXzxHLj
You have to enable CORS on the server hosting http://xxxxx.com/YYYY.xml, not on the server hosting your HTML document (which is localhost in your example).
You can't give yourself permission to access another server.
Related
I'm downloading a file from cross-domain and its working both in chrome and Firefox but not working in safari. Both Chrome and Firefox are downloading where as Safari is playing the song. It's safari bug but solved by somebody and I didn't quite get it. Please do help me.
Note: Giving a small error : Failed to load resource: Frame load interrupted
Clientside code:
var url = "http://www.example.com/song.mp3";
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = 'FileName.mp3';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
ServerSide Code:
.htaccess file
<FilesMatch "\.('mp3')$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
The problem is browser compatibility of Safari browser in effective usage of the Blobs. So I just removed the above snippet and used the basic anchor tag for my operations.
if(navigator.userAgent.indexOf("Safari") != -1){
var a = $("<a>").attr("href", url).attr("download", "MyFile.mp3").appendTo("body");
a[0].click();
a.remove();
}
I am preparing a JavaScript. Below is the code for the same:
<html>
<head>
<body>
<script>
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://example.com/lol.json', function(data) {
alert('Your Token is: ' + data.token);
}, function(status) {
alert('Something went wrong.');
});
</script>
</body>
</head>
</html>
So, this snipped is without "access-control-allow-origin" and I am running this locally, so I have used file:/// by disabling the security features of chrome.
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
I need to run this one without disabling the security features means by adding the request headers like:
res.setHeader('Access-Control-Allow-Origin', "http://"+req.headers.host+':8000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
Actually, I am not too good in JavaScript and messing with the same since morning. Can Any one help me regarding this that how I merge these request headers in the snippet.
You will have to update the startup of the chrome by using the following :
-disable-web-security -user-data-dir
You can add this to response header in your server side:
file://
I have a method WCF, which returns a JSON:
enter image description here
the client has a script that should take the data from the wcf service
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
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;
}
$(document).ready(function () {
$('#btn').click(function () {
$.ajax({
url: 'http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories',
method: 'get',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success:function(data)
{
alet(data.Announcing[0].Categories.id);
},
error: function (error)
{
alert(error);
}
})
var request = createCORSRequest("get", "http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories");
request.send();
})
})
</script>
<input id="btn" type="button" />
After click button i have this error: Object object
and i have console message:
SCRIPT7002: XMLHttpRequest: Network error 0x80070005, Access Denied .
SEC7120: Source http: // localhost: 4945 is not found in the header Access-Control-Allow-Origin ..
How to solve these problems?
Well, because your web server is running locally (see the 192.168...) address, I can't test it, but your error messages tell me the following:
The first one indicates that you are trying to access an unavailable resource. Try visiting the url with your browser, and see if that gives a response. Also in, http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories, the double slash might indicate it's the wrong url.
The second error is not complete, but are you maybe serving the web page from a different server than the api? Because a quick google search reveals that it has something to do with a cross-site request.
I'm trying to get an html content to an external url using ajax request and load it to specific div element but I'm having error by doing the cross domain ajax request
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://www.myowndomain.com/embed.php?c=5576b014b210a. (Reason:
CORS header 'Access-Control-Allow-Origin' missing).
This is the sample code that must be pasted in any blogs, forum or website of a users (any domain):
<script type="text/javascript" src="http://myowndomain.com/embed.js"></script><script type="text/javascript">embed.init(["5576b014b210a", "myembeded"]);embed.myCollage();</script><div id="myembeded"></div>
then here's the code for embed.js resided in my domain
var embed = embed || (function(){
var _args = {};
return {
init : function(param) {
_args = param;
},
myCollage : function() {
embed.load_home(_args[0],_args[1]);
},
load_home:function (id,elementId) {
var request = embed.createCORSRequest("get", "http://myowndomain.com/embed.php?c="+id);
if (request){
request.onload = function(){
document.getElementById(elementId).innerHTML = request.responseText;
};
request.send();
}
},
createCORSRequest:function (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;
}
};
}());
and for the embed.php resided in my domain
if(isset($_GET['c'])){
echo file_get_contents('http://myowndomain.com/embed/?u='.$_GET['c']);
}
This is a feature implemented into browsers to prevent you from performing requests that aren't on your local domain.
If the other site has an API that allows that, then use their API. Otherwise you can't get the data. If it's your site, modify your web server to enable the requests by adding the header info.
This is all info that could have been gotten by just looking up the error yourself.
Already solved it. by adding this to my embed.js:
header("Access-Control-Allow-Origin: *");
Thanks for the idea.
I am trying to consume the weather web service provided by wsf.cdyne.com/WeatherWS/Weather.asmx. I am sure that I can get a response in XML format by using the uri " 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=' + zipcode".
So what I want to do now is sending the uri above using XmlHttpRequest. I added some alerts to monitor the status. After open() the readyState is 1. After that I can't get any other response. If I remove the statement "xmlHttpRequest.onreadystatechange = processRequest;", I cannot see any response after send(). So I just hope someone can help me to check what is wrong.
<html>
<head>
<title>weather app</title>
</head>
<body>
<script language="JavaScript">
function httpGet()
{
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
xmlHttp.open( "GET", "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=85281", false );
alert("1 " +xmlHttp.readyState);
xmlHttpRequest.onreadystatechange = processRequest;
alert("2 " +xmlHttp.readyState);
xmlHttp.send();
alert("3 " +xmlHttp.readyState);
document.write(xmlHttp.responseText);
return xmlHttp.responseText;
}
httpGet();
</script>
</body>
</html>
As correctly stated by #robertklep this request is cross-domain. Browsers disallow cross-browser requests as a security measure so you don't hijack the user's sessions on their sites etc.
To get it to work you can create a proxy on the local site. If the site offers support to use JSONP cross-domain, you could use that.
For more information lookup some information on cross-domain policies or if they have some API docs, they may have information there on your problem too.