This question already has answers here:
Cross origin requests are only supported for HTTP but it's not cross-domain
(9 answers)
Closed 7 years ago.
I have been using an HTTP request in a JS file to retrieve information from a local JSON file. It works just fine on my Windows computer in Firefox and Chrome, but when run on a Mac, the Chrome debugger throws an error saying that Cross origin requests are only supported for HTTP...
My HTTP request code is as follows:
var xhr = new XMLHttpRequest();
xhr.open("GET", "sample.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 305) {
var myData = JSON.parse(xhr.responseText);
window.myData = myData;
showAll(myData);
}
}
};
xhr.send(null);
Any ideas? Thanks
Yes, this is a security issue. You need to run this on a server, and the file:/// protocol is not supported for such kind of requests! AJAX is a proper HTTP request response kind of concept and you cannot use file:/// protocol or use different protocols for the transaction.
Related
I am trying to debug a functionality that runs from a plain old Javascript Web Page and requests to a server.
This perfectly works on my computer but fails on another (the real target)
When it fails, i get an empty string response from the server.
Here is the code that build the request
// Send request to web server
var url = "/start?f="+filesDesc[iFile].name+"&ft="+ft+"&t="+time0ms;
var req = new XMLHttpRequest();
if (req) {
req.open("POST", url, true);
// Hack to pass bytes through unprocessed.
req.overrideMimeType('text/plain; charset=x-user-defined');
req.timeout = 2000;
req.onreadystatechange = function(e) {
// In local files, status is 0 upon success in Mozilla Firefox
if(req.readyState === XMLHttpRequest.DONE) {
var status = req.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.debug(req.responseText);
} else {
console.debug("startPlaying : error while sending rqst" );
}
}
};
req.send();
}
I noticed that on my computer (working) the output header of the request looks like this :
POST /start?f=2021-02-09_14;05;40&ft=1612880820756.4346&t=1614243685530 HTTP/1.1
On the target computer (FAIL) it looks like :
POST /start?f=2021-02-09_14;05;40&ft=1612879543815&t=1614183852864 undefined
Notice the "undefined" protocol information
I wonder what can produce such a difference knowing that :
The computer are the same 'Asus ZenBook'
Navigator are the same : Mozilla Firefox 85.0.2 (32 bits)
Network drivers are the same
Client and Server code are the same.
This is very strange behaviour.
Many thanks for any precious piece of information !
We find out that this behaviour was a side effect of a DOM exception caused by registering activeX filters. Our application also tried to load video with calls to :
navigator.mediaDevices.getUserMedia({video: { deviceId: device.deviceId }})
This was ending in an :
Uncaught DOMException: A network error occured.
Believe me or not, removing activeX filters removes the network error !
We felt into a problem similar to :
NotReadableError: Failed to allocate videosource
This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Request succeeds on server but results in CORS error in browser
(2 answers)
Closed 3 years ago.
Is it possible to make an HTTP POST request from JavaScript to any
domain name?
Javascript
var xhr = new XMLHttpRequest();
xhr.open("POST", 'URL linki', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
and I would like print on the screen. Is it possible?
Yes, it's possible to make a request to any domain as long as the domain in question accepts the request, and the server allows CORS (Cross-Origin Resource Sharing). The latter is only required if you want a response, as you're sharing resources across origins.
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
I am hosting a webpage in WAMP and keep on receiving this error in the Chrome Developer Console
GET http://localhost/surveys/Internet.json survey.js:368
my survey.js line 368 is in this function`
function loadJSON(key,json){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var obj = xhr.responseText;
localStorage.setItem(key,obj);
}
}
};
xhr.open("GET", json, true);
xhr.send(); // <<-------------------------- line 368
}
I have no clue what is going on. I recently tried to reinstall wamp hoping it was just a conflict with another application but it did not solve anything.
Any help would be great.
It was a problem in the CACHE MANIFEST file
It must be noted in the manifest that these files need internet connection to become available which in my case I did not.
CACHE MANIFEST
#Files to store on application cache
NETWORK
#Files that would require internet connection to access
I am trying to call a web service from javascript. In Internet Explorer 9 works properly, while chrome does not work. The error is as follows:
"OPTIONS http://www.restfulwebservices.net/wcf/CurrencyService.svc?wsdl 400 (Bad Request)
XMLHttpRequest cannot load http://www.restfulwebservices.net/wcf/CurrencyService.svc?wsdl. Origin null is not allowed by Access-Control-Allow-Origin."
I leave the code for help me. Thanks.
`
function SOAPClient() {
this.wsdl = '';
this.async = true;
this.action = '';
this.xml = '';
SOAPClient.prototype.invoke = function(){
var xhr;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else {// code for IE6, IE5
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function() {
if (xhr.readyState >= 3){
alert ('ReadyState '+xhr.readyState+' - - Status '+xhr.status);
if(xhr.status == 200)
document.getElementById("txtResult").innerHTML=xhr.responseText;
else
document.getElementById("txtResult").innerHTML='Error';
}
}
xhr.open("POST", this.wsdl,this.async);
xhr.setRequestHeader("SOAPAction", this.action);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.setRequestHeader("Connection", "close");
xhr.send(this.xml);
return false;
}
}
</script>
<script type="text/javascript">
var wsdl = 'http://www.restfulwebservices.net/wcf/CurrencyService.svc?wsdl';
var action = 'GetConversionRate';
var xml = '';
var async = true;
var response = '';
function prueba(){
var client = new SOAPClient();
client.wsdl = wsdl;
client.action = action;
client.xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.restfulwebservices.net/ServiceContracts/2008/01"><soapenv:Header/><soapenv:Body><ns:GetConversionRate><ns:FromCurrency>EUR</ns:FromCurrency><ns:ToCurrency>GBP</ns:ToCurrency></ns:GetConversionRate></soapenv:Body></soapenv:Envelope>';
client.invoke();
return false;
}
</script>
</head>
<body>
<p>VersiĆ³n 2.5</p>
<form name="form" action="#">
Term: <input type="text" name="inputValue" method="post"/>
<button onclick="prueba()">Search</button>
<p id="txtResult"></p>
</form>
</body>
`
First, your request must either:
abide by the same-origin policy (i.e., requesting domain == receiving domain), or
be exclipity permitted to access the service's pages by a Access-Control-Allow-Origin header that lists your domain as a domain allowed to access that server in a cross-domain way.
Furthermore, you are making the request from a file:// document, and Chrome might disallow it from performing any cross-domain XHR, even if the server gives back an all-permissive Access-Control-Allow-Origin: *. You should run a local server to access your files through HTTP, or simply test in a different browser.
If you're on a different domain you must, as stated above, set the Access-Control-Allow-Origin header.
It also sounds like your not handling the OPTIONS request that is made at all by your application. This is just an additional request made by the browser when the type of request isn't of GET or POST. All you'll be doing is returning headers with the proper Access-Control-Allow-Origin permissions to let the browser know it's permitted to make the cross domain request.
I'm not sure what you're using in the background, but see this post to see how it was done in Rails.
How to be aple to POST, PUT and DELETE from Backbone app to Rails app on different subdomains?