XMLHttpRequest and Web Workers Access-Control-Origin - javascript

I'm dealing with some Access-Control-Origin issues when using webworkers to make an XMLHttpRequest.
The issue is easily reproducible in this code, main.js:
var worker = new Worker('js/createSimplePage.js');
worker.onmessage = function () {
console.log('message recieved');
};
And js/createSimplePage.js:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "http://search.twitter.com/search.json?q=balling&rpp=20&callback=", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send();
If I include createSimplePage.js in the header of index.html, it runs fine and prints the correct response from the twitter API. However, if I only load main.js and let it try to load createSimplePage.js as a web worker then I receive the error:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=balling&rpp=20&callback=.
Origin file:// is not allowed by Access-Control-Allow-Origin.
A similar error occurs when hosting the files on SimpleHTTPServer except the error is then
"Origin http://127.0.0.1:8000 is not allowed by Access-Countrol-Allow-Origin."
I don't understand why loading it as a web-worker would break it so it can't access the API.

I don't think webworkers have the same security level as the browser. Maybe you could ensure you scripts are returned with allow all origins header:
header("Access-Control-Allow-Origin: *");
and probably best to removed your custom header:
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
This site has more information:
http://enable-cors.org/

Related

Cross Origin GET Request CORS Error with Data Power

I am trying to connect to Denodo to pull back information via an API call, but I have to go through Data Power for security reasons. When bypassing Data Power, we are able to successfully retrieve the data from Denodo. I have been informed that everything is set up in Data Power correctly for the response headers and the configuration is set to allow our web application. Below is the code we use to make the call:
var xhr = new XMLHttpRequest();
xhr.open("GET", "target URL", true);
xhr.withCredentials = true;
xhr.setRequestHeader('Access-Control-Allow-Origin', 'source URL');
xhr.setRequestHeader('Access-Control-Allow-Credentials', 'true');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.response);
console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
We receive the following error in the console when executing the function:
Access to XMLHttpRequest at 'target URL' from origin 'source URL' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
We have tried a variety of different options to get this to work, but we still can't. I've searched the forums for similar issues, and the responses have been tried unsuccessfully.

Chromes security stops me from sending emails, would android also stop it?

I'm making a Cordova app. I have an email sending function, when i test my app in chrome i get the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have looked through out stack overflow and havent been able to find a solution. Nothing ive seen has worked. Some people say this problem is specific to chrome and other browsers. If its only browsers that are the problem when i run my app on android everything should be fine and the email should send, right? Heres the code if you wanted to see:
var message = localStorage.getItem("Message");
var key = "xxthisisakeyxx";
var message_name = "send_message";
var data = {};
data.value1 = message;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://example.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
console.log(JSON.stringify(XMLHttpRequest));
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader( 'Access-Control-Allow-Origin', "http://localhost:8000");
xmlhttp.setRequestHeader( 'Content-Type', 'application/json' );
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
Thank you
The problem would be the access-control on the server side script.
Example: If you are posting the data to a php script you may need to include this line at the top of the .php file:
header('Access-Control-Allow-Origin: *');
This can be unsafe but if you are posting the data from inside a Cordova app it may be hard to specify an exact origin.

Unable to retrieve data from http site to https using XMLHttpRequest()

I have a site hosted on https:// in which I want to pull data from the site which shows the properties of the shares. The URL which returns the data is:
http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
The code which I have developed to get the data is as follows:
function GetSharesUpdate(){
// makeing AJAX calls to the web service for getting the share update
var xhr = new XMLHttpRequest(); // Set up xhr request
xhr.open("GET", "http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191", true); // Open the request
xhr.responseType = ""; // Set the type of response expected
xhr.send();
// Asynchronously wait for the data to return
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var tempoutput = xhr.responseXML;
alert(tempoutput);
}
}
// Report errors if they happen
xhr.addEventListener("error", function (e) {
console.error("Error: " + e + " Could not load url.");
}, false);
}
I am getting the error on the statement xhr.send(); which is as below:
Mixed Content: The page at 'https://[SiteUrl]' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint
'http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191'.
This request has been blocked; the content must be served over HTTPS.
If I change the URL to https i.e.
https://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
then xhr.send(); is executed without any error but I am getting xhr.responseXML null.
What should I make changes in my code to make it working?
The first problem is you are doing ajax request to non-https domain but your domain has SSL installed.
The second problem is Cross origin request CORS, you will have this problem even you solve first (ie. even you try ajax request from non-http domain).
Since you are requesting data from another website this is most likely to happen unless the requested server is configured to serve requests for you domain
To solve this you need to call the data from your server(proxy server) or have the requested server configured to allow requests from your domain.
See more - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Cross-domain post to external site fails on wordpress

I'm trying to post data to an external website from a wordpress site using Javascript, however when i send the form i'm getting this:
XMLHttpRequest cannot load https://external_site.com/embed/documents.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://my_site.com' is therefore not allowed access.
The response had HTTP status code 404
I'm trying to this from a Wordpress site, this is the Javascript part that sends the data
jQuery('#send_doc').click(function(){
var url = jQuery('#document_url').val();
var name = jQuery('#name').val();
var request = new XMLHttpRequest();
request.open('POST', 'https://external_site.com/embed/documents');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Token my_token
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'document_url': url,
'name': name
};
request.send(JSON.stringify(body));
});
My question is, i understand that this is a Cross-domain problem, but my question is: Can i resolve the problem by my side or is this problem just on the externa site side?
Thank you very much for your answers

XMLHttprequest not working the twitch.tv api

So I've been trying to access the twitch.tv api but every time i go to make a request i keep on getting the error:
"XMLHttpRequest cannot load https://api.twitch.tv/kraken/streams/normalice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access."
I'm currently using the live-server package during the development process other wise I'm just using html, css, javascript. Here is my javascript:
var req = new XMLHttpRequest();
var url = 'https://api.twitch.tv/kraken/streams/normalice';
req.open("GET", url, true);
req.send();
req.onreadystatechange = function () {
if (req.status == 200 && req.readState == 4){
// do stuff here
console.log('hurray it worked');
}else{
console.log(req.statusText);
console.log(req.responseText);
}
}
Does anyone have any ideas as to why am I encountering this error?
The Twitch.tv API doesn't support CORS. You need to use JSON-P (aka JSONP) to work around it. Read more about that in the Twitch.tv API docs. There is a prior answer on how to make a JSONP request with native JavaScript that may be useful.

Categories