XMLHttpRequest和Web Workers访问控制源

XMLHttpRequest and Web Workers Access-Control-Origin

本文关键字:访问控制 Workers Web XMLHttpRequest      更新时间:2023-09-26

我正在处理一些访问控制原点问题,当使用webworkers制作XMLHttpRequest。

这个问题很容易在main.js中重现:

var worker = new Worker('js/createSimplePage.js');
worker.onmessage = function () {
  console.log('message recieved');
};

和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();

如果我在index.html的头文件中包含createSimplePage.js,它会运行良好,并从twitter API打印正确的响应。然而,如果我只加载main.js,让它尝试加载createsimplpage .js作为一个web工作者,然后我收到错误:

XMLHttpRequest cannot load http://search.twitter.com/search.json?q=balling&rpp=20&callback=. 
Origin file:// is not allowed by Access-Control-Allow-Origin.

在SimpleHTTPServer上托管文件时也会出现类似的错误,但错误是

 "Origin http://127.0.0.1:8000 is not allowed by Access-Countrol-Allow-Origin."

我不明白为什么加载它作为一个网络工作者会破坏它,所以它不能访问API

我不认为网络工作者具有与浏览器相同的安全级别。也许你可以确保你的脚本返回允许所有起源头:

header("Access-Control-Allow-Origin: *");

,最好删除自定义标题:

xmlhttp.setRequestHeader('Content-Type', 'text/plain');

这个网站有更多的信息:http://enable-cors.org/