【问题标题】:JQuery AJAX request fails with CORS error if modifying XHR如果修改 XHR,则 JQuery AJAX 请求失败并出现 CORS 错误
【发布时间】:2016-03-30 19:37:40
【问题描述】:

我正在使用 JQuery 将文件上传到服务器,并且工作正常。由于一些用户会上传大文件,我想添加一个进度条,这就是事情变得时髦的地方。我找到了大约 10 种不同的解决方案(包括这里),但它们都不适用于我的场景。

我发布到不同的来源(这是我无法改变的事实)。这有效:

 $.ajax({
    url: "xxx",
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            console.log('Success');
        }
        else
        {
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        console.log('ERRORS: ' + textStatus);
    }
});

但是我一触碰XHR对象,比如这里要添加一个onprogress监听器:

Can onprogress functionality be added to jQuery.ajax() by using xhrFields?

我的代码变成了:

 $.ajax({
    url: "xxx",
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    xhr: function()
    {
      var xhr = new window.XMLHttpRequest();
      xhr.upload.addEventListener("progress", function(evt){
        if (evt.lengthComputable) {
          var percentComplete = evt.loaded / evt.total;
          console.log(percentComplete);
        }
      }, false);
      return xhr;
    },
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            console.log('Success');
        }
        else
        {
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        console.log('ERRORS: ' + textStatus);
    }
});

我在浏览器中收到以下错误:

跨域请求被阻止:同源策略不允许读取 xxx 处的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

使用 Firefox 进行测试,但更改不是一个真正的选择,这需要在大多数流行的浏览器上工作。

所以基本上,我可以发布跨域并且它可以工作。只要我想监控它的进度,它就会失败。

我尝试过的其他方法:

  • 将 onprogress: 添加到 $.ajax()
  • 使用 XHRFields
  • 各种不同形式的xhr:function()

我一接触 XHR 对象,就会被 CORS 拒绝。万一你想知道,网络服务器(Apache)是这样设置的:

Header set Access-Control-Allow-Origin "*"

感谢您的意见,我已经在这工作了好几个小时了,无法展示血腥的进展。在这方面花费的时间比实际应用程序本身要多。

这是 JQuery 1.7.1 - 我无法升级它。

有没有人知道为什么我修改 xhr 对象时不允许使用不同的来源?

干杯

斯蒂芬

【问题讨论】:

    标签: jquery ajax xmlhttprequest cors


    【解决方案1】:

    如果您在本地测试,请尝试在 url 中使用 localhost 而不是 0.0.0.0 ,如果可行,请告诉我

    【讨论】:

    • 我没有在本地测试 - 我真的没有选择这样做。
    • 我在 POST 中使用的 URL 是这种形式:host:port/mod_owa/procedure
    猜你喜欢
    • 2014-08-02
    • 2013-12-06
    • 2021-12-13
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多