【问题标题】:XMLHttpRequest and Web Workers Access-Control-OriginXMLHttpRequest 和 Web Workers Access-Control-Origin
【发布时间】:2013-06-05 07:13:48
【问题描述】:

在使用 webworkers 发出 XMLHttpRequest 时,我正在处理一些 Access-Control-Origin 问题。

这个问题很容易在 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 并让它尝试加载 createSimplePage.js 作为网络工作者,那么我会收到错误:

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。

【问题讨论】:

    标签: javascript html xmlhttprequest web-worker


    【解决方案1】:

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

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

    并且可能最好删除您的自定义标题:

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

    此网站有更多信息: http://enable-cors.org/

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2013-04-12
      • 1970-01-01
      • 2019-08-15
      • 2016-12-09
      • 1970-01-01
      • 2013-01-24
      • 2019-06-06
      • 2016-02-06
      相关资源
      最近更新 更多