can not load local xml file through xmlhttprequest - javascript

I am using XAMPP Apache on port 80.
When I try with localhost in the url I get:
XMLHttpRequest cannot load http://localhost/ice_escape/pokus.xml. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
and also:
Uncaught TypeError: Cannot read property '0' of null
I tried allowing CORS by adding this to httpd.conf to no avail:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Then I tried changing localhost to 127.0.0.1. It removes the first error, but the other error persists.
var url = "http://127.0.0.1/iceescape/pokus.xml";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
txt = xmlhttp.responseText;
{//---- some code that parses the xml
var strWidth = "width";
var a = txt.indexOf(strWidth);
a += strWidth.length;
txt = txt.slice(a,(txt.length) );
var width = txt.match(/\d+/)[0];// here it says its null
}
}
}
};
xmlhttp.send();
the xml:
<?xml version="1.0" encoding="UTF-8"?>
<map width = "2400" height = "1800">
<ghost type="troll" speed="5">
<point>
{100,200}
</point>
<point>
{350,250}
</point>
</ghost>

What you are trying to read with XHR is not a local file.
You have origin null (which means your HTML document is a local file, loaded via the file:// URL scheme) and you are making the Ajax result to http://localhost/ice_escape/pokus.xml which is an HTTP resource on the same computer.
Load your HTML document from the web server too.

Related

How to POST json data to the server? (CORS error)

My goal
I am doing .aspx file on Microsoft Visual Studio. What I expect is that the system will scan the QR code and then send the JSON data to the server side.
PS. I am using XMLHttpRequest to send the data.
What I Get
First I tried to pass it directly, it does not work so I check its status and readyStats, what it shows is 1(open) and 0(not initialized) (I am expecting 4(done) and 200(ok)) the responseText is null. I then inspected my browser (Google Chrome), the console shows an error "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
What I tried
So I searched for solution on stack overflow, most of them says that I need to put in the header Access-Control-Allow-Origin:* to the server, but the problem is I do not have the control of the server but I do contacted them to change the code to try it out, end up Access-Control-Allow-Origin:* doesn't work so I looked for alternative. I tried to use plugin such as Moesif Origin & CORS Changer but it shows "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.".
Below is my code:
function onScanSuccess(qrCodeMessage) {
...
var url = "https://Website-A.aspx";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
//I hardcoded the data for testing
var data = {
"SOME_ID": "Value",
"SOME_TYPE": "Value",
"SOME_ID": "Value",
"SOME_AMT": "Value",
"SOME_AMT_CURRENCY": "Value",
"SOME_DESC": "Value",
...
};
xhr.send(data);
}
Is there anyway to solve this without changing the server side's code or bypassing the CORS?
I wish to solve this by modify the code in the same .aspx only, is it possible?
If my code ain't going to work, is there any other way to do it?
Any helps will be appreciated.
cors must be allowed on server side. your code looks ok.
sorry, i can't use the comment function yet

Access-Control-Allow-Origin Apache SVN endpoint

I would like to make a XmlHttp GET request from client Javascript to a Apache SVN endpoint and I'm facing the following error:
Failed to load http://IP_ADDRESS/svn/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://IP_ADDRESS:3000' is therefore not allowed access.
I've tried set the Header set Access-Control-Allow-Origin "*" in the following files and no success so far.
/etc/apache2/mods-available/dav_svn.conf (the configuration is inside this file)
.htaccess (inside the endpoint root folder)
I'm running out of ideias how to do it.
The Javascript request code:
var xmlhttp = new XMLHttpRequest();
// encodedData = ...
xmlhttp.open('GET', url, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + encodedData);
xmlhttp.withCredentials = true;
xmlhttp.send();
What am I doing wrong?
Have you tried adding the address of the client instead of *?
Header set Access-Control-Allow-Origin "http://IP_ADDRESS:3000"
Also if it doesn't work I would suggest adding these other options:
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"

Userscript cross-origin request failing

My AJAX function:
function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
var xmlHttpRequest = new XMLHttpRequest();
var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
xmlHttpRequest.open(method, url, async);
xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
xmlHttpRequest.withCredentials = true;
if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
xmlHttpRequest.send(param);
if(!async) { callback(xmlHttpRequest); }
}
Function call:
ajaxQuery('http://example.net/index.php', 'GET', null, true, function(r) {
tmp.innerHTML = r.responseText;
nlt = [].map.call(tmp.querySelectorAll('.nlt'), function(x) { return x.textContent; });
});
Headers set in PHP:
header('Access-Control-Allow-Origin: https://example.com');
header('Access-Control-Allow-Origin: https://www.example.com');
header('Access-Control-Allow-Origin: http://example.net');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Credentials: true');
if(!preg_match('%https?:\/\/(www\.)?example\.com%', $_SERVER['HTTP_REFERER']) && !preg_match('%https?:\/\/example\.net%', $_SERVER['HTTP_REFERER'])) { die('No way!'); }
I am calling the userscript from a page that uses https, and my domain uses http. When I try AJAX through http, I get (Firefox) Blocked loading mixed active content. If I switch the query URL to https, the error changes to Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource, even though my PHP script clearly allows for requests from the external site. What am I missing?
In this particular example, my site is "http://example.net" and the external site is "https://www.example.com"
It is impossible to get an external resource through AJAX, JSONP or iFrames if the protocols don't match, at least in Firefox and Chromium, due to stupid "mixed content" restrictions. My website is running over http, and the website for which the userscript has been written has enforced https (meaning trying to request its pages through http automatically redirects to https, so I can't even work around the restriction by opting in for http).
The Access-Control-Allow-Origin header should be the same value as the Origin header as long as you want to allow it.
So. you want to multiple domains. I'm recommend you using 'regex'

Access-Control-Allow-Origin' header contains multiple values 'http://xx.xx.xx.xx:3002, http://xx.xx.xx.xx:3002', but only one is allowed

I have downloaded a windows executable file and I installed it. The service will be listening on localhost:11100 port.
I have a written a javascript code to connect to the port and running this javascript code on any webserver is failing, because server sending multiple Access-Control-Allow-Origin headers in the response.
But if I write my JavaScript code in plain html page locally and open it in browser then it is sending one 'Access-Control-Allow-Origin' in the response.
Below is the Javascript code:
function RDService(){
var url = "http://127.0.0.1:11100";
var xhr;
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number{
//IE browser
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//other browser
xhr = new XMLHttpRequest();
}
xhr.open('RDSERVICE', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
var status = xhr.status;
if (status == 200) {
alert(xhr.responseText);
//Capture(); //Call Capture() here if FingerPrint Capture is required inside RDService() call
console.log(xhr.response);
} else {
console.log(xhr.response);
}
}
};
xhr.send();
}
after calling the RDService function below error is throwing by the service:
Failed to load http://127.0.0.1:11100/: Response to preflight request
doesn't pass access control check: The 'Access-Control-Allow-Origin'
header contains multiple values 'http://xx.xx.xx.xx:3002,
http://xx.xx.xx.xx:3002', but only one is allowed. Origin
'http://xx.xx.xx.xx:3002' is therefore not allowed access.
The windows executable should only be returning one domain or * in the Access-Control-Allow-Origin header. This is not an issue with the client side JavaScript.
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
*
For requests without credentials, the server may specify "*" as a wildcard, thereby allowing any origin to access the resource.
<origin>
Specifies a URI that may access the resource.
reference:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

CORS - No 'Access-Control-Allow-Origin' header is present

I'm hosting a website that has a number of different domain names pointing at it.
lets call the hosted website example.com and the url-forwarded domain names - example-x.com, example-y.com, example-z.com
When the url-forwarded domains are visited, cross domain requests are made back to the host site, example.com.
I'm currently making ajax GET requests to json files and receiving the following error;
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example-x.com' is therefore not allowed
access.
Even though the preflight OPTIONS return a status of 200 and the GET method returns a status of 200.
OPTIONS;
GET
I have set the following CORs headers on the host htaccess;
# <IfModule mod_headers.c>
SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>
And i'm call GET using the following ajax request;
var 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;
};
var url = 'http://example.com/data.json';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = function() { console.log('success');};
xhr.onerror = function() { console.log('error'); };
xhr.send();
EDIT
Removing setRequestHeader("Content-Type", "application/json; charset=UTF-8") from the ajax request has removed the preflight requirement, however the CORs error still persists, the screenshot below shows the request / response of GET, its my guess that the correct htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
GET - WITHOUT OPTIONS PREFLIGHT
You are trying to retrieve a json by a GET request. This should be a simple request, and it does not need to have a preflight request.
If you look at the requirements for a preflight request from MDN, you can see that setting Content-Type other than application/x-www-form-urlencoded, multipart/form-data or text/plain will cause this preflighted request.
If you look at the content-type from the RFC, it is a "SHOULD" for "a message containing a payload body". But your get request does not have a payload. As a result remove that header from your ajax call.

Categories

Resources