【问题标题】:Possible CORS issue. What's going on and how can I fix it?可能的 CORS 问题。发生了什么事,我该如何解决?
【发布时间】:2015-11-12 15:15:24
【问题描述】:

我正在访问 REST Web 服务,使用异步请求加载查询数据。当我在不同的服务器上运行相同的代码时(例如,我在本地开发,然后访问网络上的实时版本),AJAX 请求将失败。清除缓存,刷新页面,就可以了。

失败时我得到的错误(从 chrome 控制台复制/粘贴,也发生在 FF 中)是:

XMLHttpRequest cannot load http://www.flymine.org/query/service/model?format=json. The 'Access-Control-Allow-Origin' header has a value 'http://fiddle.jshell.net' that is not equal to the supplied origin. Origin 'http://null.jsbin.com' is therefore not allowed access. im.js:129
Uncaught TypeError: Cannot read property 'content-type' of undefined http://www.flymine.org/query/service/summaryfields?format=json.
The 'Access-Control-Allow-Origin' header has a value 'http://fiddle.jshell.net' that is not equal to the supplied origin.  
 Origin 'http://null.jsbin.com' is therefore not allowed access. im.js:129 
 Uncaught TypeError: Cannot read property 'content-type' of undefined

这很容易重现:

  1. 访问代码on one server (JSBin)。您应该会获得成功的输出,说明查询返回的外显子数量。
  2. 访问相同的代码on a different server (JSFiddle)。如果使用 chrome,请确保您的开发人员工具已关闭,因为它们往往会为您清除缓存并防止错误发生。输出窗格应显示错误,直到您清除缓存并再次运行 jsfiddle。

我很确定我需要启用一些 CORS-ey,但我不完全确定它可能是什么。我确实有权根据需要修改服务器标头等以防止出现此问题。

有一个库,IMJS,负责通信的大部分工作,但这是连接的基本代码:

  var flymine   = new imjs.Service({root: 'www.flymine.org/query'});
  var query     = {
    from: 'Gene',
    select: [
      'exons.symbol',
      'chromosome.primaryIdentifier',
      'exons.chromosomeLocation.start',
      'exons.chromosomeLocation.end'
    ],
    where: {
      symbol: 'eve',
      organism: {lookup: 'D. melanogaster'}}
  };
  flymine.rows(query).then(function(rows) {
    console.log("No. of exons: " + rows.length);
    rows.forEach(function printRow(row) {
      console.log("[" + row[0] + "] " + row[1] + ":" + row[2] + ".." + row[3]);
    });
  });

【问题讨论】:

    标签: javascript ajax cors intermine


    【解决方案1】:

    错误消息几乎为您说明了问题:

    XMLHttpRequest 无法加载 http://www.flymine.org/query/service/model?format=json

    您尝试访问的服务器是www.flymine.org

    “Access-Control-Allow-Origin”标头的值为“http://fiddle.jshell.net

    www.flymine.org 表示允许http://fiddle.jshell.net 从中读取数据。

    www.flymine.org 通过在响应中添加 Access-Control-Allow-Origin 标头来实现此目的。

    不等于提供的原点。因此,Origin 'http://null.jsbin.com' 不允许访问。 im.js:129

    您的请求来自http://null.jsbin.com,而不是http://fiddle.jshell.net

    您需要更改www.flymine.org,以便它授予http://null.jsbin.com 的权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      相关资源
      最近更新 更多