【问题标题】:CORS problem with XMLHttpRequest from localhost to REST service with FireFox使用 FireFox 从 localhost 到 REST 服务的 XMLHttpRequest 的 CORS 问题
【发布时间】:2019-03-07 13:36:04
【问题描述】:

现在,当我使用 IIS 服务器在我的本地主机上打开一个开发页面并尝试使用 FireFox 为另一台服务器上的 REST 服务创建一个 XMLHttpRequest 时,我收到了这个错误:

跨域请求被阻止:同源策略不允许读取 远程资源在 https://carto48dev.education.gouv.qc.ca/arcgis/rest/services/DEV/AUTH_SERVICES/GPServer/Login/execute。 (原因:CORS 标头“Access-Control-Allow-Origin”不匹配 ‘https://localhost:8080’)。

这个问题似乎是 FireFox(版本 62.0.2)中的新问题,因为它以前可以工作,而我在使用 Chrome 或 IE 时没有这个问题。

我想了解为什么它以前可以工作而不是现在,以及为什么它仍然在 Chrome 中工作但在 FireFox 中没有

最有可能是 REST 服务或 FireFox 安全中的某些内容发生了更改?

这是来自 REST 服务的响应标头:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080
Cache-Control: max-age=0,must-revalidate, max-age=60
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/plain;charset=utf-8
Date: Tue, 02 Oct 2018 12:30:29 GMT
Expires: Tue, 02 Oct 2018 12:41:30 GMT
Keep-Alive: timeout=15, max=100
Set-Cookie: UqZBpD3n3iPIDwJU9Am+pGqSSQ@@=v…Sep-2028 12:30:28 GMT; Path=/
Transfer-Encoding: chunked
Vary: Origin
Vary: Accept-encoding

这是我制作XMLHttpRequest的方法:

function makeRequest(url, postData, options)
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        url = options.method == "GET" ? url + "?" + _encodePostData(postData) : url;
        xhr.open(options.method, url, options.async);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var response = JSON.parse(xhr.response);
                //service internal error
                if (response.results[1].value) {
                    reject(response.results[1].value);
                } else {
                    resolve(response.results[0].value);
                }
            }
        };
    });
};

【问题讨论】:

    标签: javascript firefox cors xmlhttprequest


    【解决方案1】:

    最后,进一步调查证明问题出在 FireFox 插件中,即:DuckDuckGo Privacy Essentials

    【讨论】:

      【解决方案2】:

      您需要在服务器端添加 CORS 标头

      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
      header("Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token"); 
      

      【讨论】:

      • 好的,谢谢,您知道为什么它以前可以工作而不是现在,为什么它仍然可以在 Chrome 中工作,但不能在 FireFox 中工作?
      • 浏览器处理 AJAX/XMLHttpRequest 的方式不同,我们需要在服务器端提供适当的标头
      猜你喜欢
      • 2019-03-17
      • 2017-02-18
      • 2020-12-06
      • 2023-03-06
      • 1970-01-01
      • 2020-09-11
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多