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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.