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://
Related
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET','http://example.com/',true);
xmlHTTP.send();
I just keep getting XHR failed loading: GET, can anyone help???
Thanks
If the server your contacting doesn't have CORS set in the header (e.g. access-control-allow-origin: *), you will not be able to make the request. If you don't have access to the server to set a CORS header, you'll need to contact the server from a server you do control and then pass that to the browser (either with a CORS header or not if it's served from the same domain)
But your code works fine. The problem is with your http://example.com/ not returning
http://jsbin.com/zuhobidako/edit?html,js,console,output
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET','https://jsonplaceholder.typicode.com',true);
xmlHTTP.send();
xmlHTTP.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.body.innerHTML =
this.responseText;
}
};
For server status errors, add this to onreadystatechange
if( this.status > 299 && this.readyState == 4) {
console.log('Server Error: ' + xmlHTTP.statusText);
}
For xmlHTTP code errors...
xmlHTTP.onerror = function() {
console.log('xmlHTTP Error', xmlHTTP.responseText)
}
I am using dojo.request.xhr to make a post reqeust to geoserver.
But the problem is when i'm using XMLHttpRequest to make the post request , it is working fine on the other hand when i'm using dojo.reqeust.xhr for the same thing its giving the following error.
*
org.xmlpull.v1.XmlPullParserException: only whitespace content allowed
before start tag and not i (position: START_DOCUMENT seen i... #1:1)
only whitespace content allowed before start tag and not i (position:
START_DOCUMENT seen i... #1:1)
*
dojo.request.xhr code -
xhr(url, {
handleAs : "xml",
data : postData,
method : "POST",
headers : {
'Content-Type' : 'text/xml',
},
}).then(function(data){
console.log(data);
}, function(err){
console.log("Error : " + err);
});
above code is not working and giving the above mentioned error.
This is same post request using the XMLHttpRequest :-
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader('Content-type', 'text/xml');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
alert("Error");
return;
}
var xml = req.responseXML;
console.log(xml);
}
if (req.readyState == 4) return;
req.send(postData);
To check the XML(that i'm sending as postData) whether it is valid or not i used GeoServer's demo request tool to build the WFS request and its working fine.
UPDATE :- This is the link of XML file that i'm sending as a postData.
post_XML_File
Can anyone have any idea what i'm doing wrong?? Thanks in advance.
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 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.
Well, i'm currently developping a Google Chrome extension and i need to fetch all the DNS and 404 error to make a redirection. The problem is simply that i really don't see how it's possible...
If it's a domain error i want to fetch the domain name and for a 404 error i want to fetch the name page.
Example :
Bad Domain : http://www.justforthetest.com/ => Fetch justforthetest
404 Error : http://www.valeriemates.com/professinal.html => Fetch professinal
Hope someone could provide me some helps...
Thanks in advance !
Well, the most I was able to do is to send a new XHR request to this URL and check returned status. For wrong domains status seems to be 0, for 404 pages it is 404.
background.html
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading") {
var xhr = new XMLHttpRequest();
xhr.open("GET", tab.url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status == 0) {
console.log("wrong domain:", tab.url);
} else if(xhr.status == 404) {
console.log("404 page:", tab.url);
} else if(xhr.status == 200) {
console.log("regular page:", tab.url);
}
}
}
xhr.send();
}
});