jquery jqXHR.getResponseHeader('Location')为null

时间:2014-03-07 17:53:54

标签: jquery ajax cors

在我的ajax调用中responseHeader('Location')是FF总是空的。有谁能够帮我?顺便说一句,这是一个CORS。

$.ajax({
                url: VIDEOS_UPLOAD_SERVICE_URL,
                method: 'POST',
                contentType: 'application/json',
                headers: {
                    Authorization: 'Bearer ' + accessToken,
                    'x-upload-content-length': file.size,
                    'x-upload-content-type': file.type
                },
                data: JSON.stringify(metadata)
            }).done(function(data, textStatus, jqXHR) {
                resumableUpload({
                    url: jqXHR.getResponseHeader('Location'),
                    file: file,
                    start: 0
                });
            });

2 个答案:

答案 0 :(得分:7)

您可以通过设置标题来修复代码的服务器站点:

Access-Control-Expose-Headers: Location

这将告诉firefox浏览器允许跨域读取Location:标头。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control#Access-Control-Expose-Headers

答案 1 :(得分:2)

看起来它是Firefox / jQuery中的一个错误:http://bugs.jquery.com/ticket/11624

看起来它可能只影响某些版本的Firefox / jQuery,并且有一个patch可以解决它。从bug tracker另一个解决方案也发布了:

define("jquery-cors-patch", ["jquery"], function ($) {

  // workaround for Firefox CORS bug - see http://bugs.jquery.com/ticket/10338

  var _super = $.ajaxSettings.xhr;
  $.ajaxSetup({
    xhr: function() {
      var xhr = _super();
      var getAllResponseHeaders = xhr.getAllResponseHeaders;
      xhr.getAllResponseHeaders = function() {
          var allHeaders = getAllResponseHeaders.call(xhr);
        if (allHeaders) {
            return allHeaders;
        }
        allHeaders = "";
        var concatHeader = function(i, header_name) {
          if (xhr.getResponseHeader(header_name)) {
            allHeaders += header_name + ": " + xhr.getResponseHeader( header_name ) + "\n";
          }
        };
        // simple headers (fixed set)
        $(["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"]).each(concatHeader);
        // non-simple headers (add more as required)
        $(["Location"] ).each(concatHeader);        
        return allHeaders;
      };
      return xhr;
    }
  });

});