【问题标题】:CORS request won't work in Firefox, works in Chrome and SafariCORS 请求在 Firefox 中不起作用,在 Chrome 和 Safari 中起作用
【发布时间】:2015-09-10 07:28:03
【问题描述】:

这个小提琴在 Chrome 中可以正常工作,但在 Firefox 中不行:http://jsfiddle.net/u5pugnbn/

index.html

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <input type="button" value="Get Data" onclick="getData()"/>
    <h1 id="output"></h1>
  </body>

  <script src ="main.js"></script>
</html>

main.js

var API_URL = "http://andr3w321.pythonanywhere.com";

function getData() {
  var output = document.getElementById('output');
  var xhr = new XMLHttpRequest();
  var url = API_URL + "/hello";
  xhr.open("GET", url, true);
  xhr.onload = function (e) {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        output.innerHTML = xhr.responseText;
      } else {
        output.innerHTML = "Error: " + xhr.statusText;
      }
    }
  };
  xhr.onerror = function (e) {
    output.innerHTML = "Error: " + xhr.statusText;
  };
  xhr.send();
}

Python 瓶服务器文件

from bottle import default_app, route, run, template, static_file, url, get, redirect, response, request

# allow requests from other domains
def enable_cors(fn):
    def _enable_cors(*args, **kwargs):
        # set CORS headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

        if request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)

    return _enable_cors


@route('/hello', method=['OPTIONS', 'GET'])
@enable_cors
def hello():
    return "hello"

application = default_app()

将静态 index.html 上传到域并将 Allow-Origin* 更改为特定域似乎没有帮助。

【问题讨论】:

  • 这对我来说似乎工作正常。预期的结果是什么?
  • 如果请求成功,h1 标头应填充“hello”。嗯,我正在运行最新的 firefox 40.0.3,刚刚从 39 更新。不确定这是否有任何影响。正如我所说,它适用于 Chromium 对我来说很好,但不适用于 firefox。它在控制台中给出了一个错误,因为在 `xhr.open("GET", url, true);` 行上冻结。
  • 在 40.0.3 (windows) 和 42.0 中工作
  • 好的,感谢您的测试。我在 ubuntu 上。
  • 检查您的 Firefox 开发者工具浏览器控制台和网络选项卡,了解正在发生的事情的任何线索

标签: javascript python firefox bottle


【解决方案1】:

原来是隐私獾阻止了请求。在我访问 index.html 后禁用它后,它工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多